On 31 Jul 2006 03:41:51 -0700,
ab*****@gmail.com wrote:
Martin Ambuhl wrote:
>> I have a program where I want to print a string
>>"457e31b2db200dc125f3e00886ff57de"
>>like "\x45\x7e\x31\xb2\xdb\x20\x0d\xc1\x25\xf3\xe0\x08\ x86\xff\x57\xde"
<snip>
Thanks a lot to all of you . Although it solved the question i had
asked .. But now i m stuck with another problem related to the query .
Actually when i put a "\x" manually in front of every two digits in the
string the string gets printed as "¦ñ²±Z˜-=§ßÉ¢Sp{¦"
The code which prints these special characters is :
int main(int argc, char* argv[])
{
char mbBuf[BUF_SIZE] =
"\xb2\xa4\xfd\xf1\x5a\xf7\xc4\xf2\x15\xe1\x90\x9b\ xe4\x70\x7b\xdb";
printf("\nThe mbBuf string is %s\n",mbBuf);
}
but when i print the string "b2a4fdf15af7c4f215e1909be4707bdb" with
the \x using the for loop it doesn't print those special chars :-(
Aha. It sounds like what you meant is not "print so that the output is
in the form \x45 ...", but "print the output you would get if you had
\x45 in the source". These are not the same. Backslash escapes
including \xXX in a string (or char) literal are converted _at compile
time_ to the specified byte value(s). For example
char mbBuf[N] = "\xb2\xa4";
(given N is >= 3) should produce the same object/executable (and
must produce the same runtime effect) as
char mbBuf[N] = {0xb2, 0xa4, 0};
or
char mbBuf[N] = {178, 164, 0};
If what you want is to extract values represented as two hex digits
each in a string, and output those values, you must do the conversion
explicitly, not expect \x to cause it to happen for you:
char xx [] = "457e"; /* etc. */
int i, x; /* in general i might better be size_t */
for( i = 0; xx[i] /* && xx[i+1] */; i += 2 ){
/* or i < strlen(xx) or with array visible i < sizeof xx - 1 */
#if ONEWAY
sscanf (xx+i, "%2x", &x);
/* in general should check return value from sscanf for error(s)
but here I assume input data is always good and don't bother */
#elif ANOTHERWAY
char yy [3] = {0};
memcpy (yy, xx+i, 2); /* extract 2 digits plus null terminator */
x = /* (int) */ strtol (yy, NULL, 16);
#elif EXPLICITWAY
x = getdig (yy[i]) * 16U + getdig (yy[i+1);
#endif
putchar (x); /* for stdout, or fputc (x, fp); */
/* or have a second buffer and copy the converted bytes into it
then fwrite or if applicable fputs or puts the whole buffer */
}
where int getdig (char d)
can be for ASCII something like
return isdigit(d)? d-'0': toupper(d)-'A'+10;
or for complete portability something like
const char digitlist [] = "0123456789ABCDEF";
return strchr (digitlist, d) - digitlist;
in each case with addition of error checks and handling
if your input data is not guaranteed good or already checked.
- David.Thompson1 at worldnet.att.net