Tuesday, February 9, 2010

More MAGIC of SPRINTF

I was making a program in which i have to convert the following input into HEX Format

Input=01234567 (i.e; any number in between 0 and 9)
I have to covert these numbers into HEX like this

Output=3031323334353637

First I had made a logic which is as follows,

#define MAX_STRING_LENGTH 256

char input[MAX_STRING_LENGTH]; input array has the input like 012345...
memset (input, 0, MAX_STRING_LENGTH);

char output[MAX_STRING_LENGTH]; output array has the output like 30313233..
memset (output, 0, MAX_STRING_LENGTH);

NOTE : <> means less than
Method 1:

for int i=0,j=0;i <>LengthOf(input);i++,j+=2
{
output[j]='3';
output[j+1]=input[i];
}

Method 2:

for(int i=0,j=0;i<>LengthOf(input);i++,j+=2)
sprintf(output+strlen(output),"%c%c",'3',input[i]);


The difference betweent the two methods is that method 2 uses sprintf() function to perform the two operations at the same time whereas method 1 takes two operations to complete it.

In method 2,it is writing two characters at once means at the backend it first writes

output[0]='3';
output[1]=input[i];

we can write any format as we like by changing the second parameter format of sprintf()

References:
http://docs.roxen.com/pike/7.0/tutorial/strings/sprintf.xml
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
http://www.rohitab.com/discuss/index.php?showtopic=11505

No comments:

Post a Comment