c - use printf to print character string in hex format, distorted results -
i want print character string in hex format,
on machine , like
ori_mesg = gen_rdm_bytestream (1400,seed) sendto(machine b, ori_mesg, len(mesg))
on machine b
recvfrom(machine a, mesg) mesg_check = gen_rdm_bytestream (1400, seed) for(i=0;i<20;i++){ printf("%02x ", *(mesg+i)& 0xff); } printf("\n"); for(i=0;i<20;i++){ printf("%02x ", *(mesg_check+i)); } printf("\n");
seed
varies among 1, 2 3....
the bytes generation funcion is:
u_char *gen_rdm_bytestream (size_t num_bytes, unsigned int seed) { u_char *stream = malloc (num_bytes+4); size_t i; u_int16_t seq = seed; seq = htons(seq); u_int16_t tail = num_bytes; tail = htons(tail); memcpy(stream, &seq, sizeof(seq)); srand(seed); (i = 3; < num_bytes+2; i++){ stream[i] = rand (); } memcpy(stream+num_bytes+2, &tail, sizeof(tail)); return stream; }
but got results printf like:
00 01 00 67 c6 69 73 51 ff 4a ec 29 cd ba ab f2 fb e3 46 7c 00 01 00 67 ffffffc6 69 73 51 ffffffff 4a ffffffec 29 ffffffcd ffffffba ffffffab fffffff2 fffffffb ffffffe3 46 7c
or
00 02 88 fa 7f 44 4f d5 d2 00 2d 29 4b 96 c3 4d c5 7d 29 7e 00 02 00 fffffffa 7f 44 4f ffffffd5 ffffffd2 00 2d 29 4b ffffff96 ffffffc3 4d ffffffc5 7d 29 7e
why there many fffff
mesg_check
?
are there potential reasons phenomenon? thanks!
here's small program illustrates problem think might having:
#include <stdio.h> int main(void) { char arr[] = { 0, 16, 127, 128, 255 }; (int = 0; < sizeof arr; ++) { printf(" %2x", arr[i]); } putchar('\n'); return 0; }
on system (on plain char
signed), output:
0 10 7f ffffff80 ffffffff
the value 255
, when stored in (signed) char
, stored -1
. in printf
call, it's promoted (signed) int
-- "%2x"
format tells printf
treat unsigned int
, displays fffffffff
.
make sure mesg
, mesg_check
arrays defined arrays of unsigned char
, not plain char
.
update: rereading answer more year later, realize it's not quite correct. here's program works correctly on system, , work on reasonable system:
#include <stdio.h> int main(void) { unsigned char arr[] = { 0, 16, 127, 128, 255 }; (int = 0; < sizeof arr; ++) { printf(" %02x", arr[i]); } putchar('\n'); return 0; }
the output is:
00 10 7f 80 ff
an argument of type unsigned char
promoted (signed) int
(assuming int
can hold values of type unsigned char
, i.e., int_max >= uchar_max
, case on practically systems). argument arr[i]
promoted int
, while " %02x"
format requires argument of type unsigned int
.
the c standard implies, doesn't quite state directly, arguments of corresponding signed , unsigned types interchangeable long they're within range of both types -- case here.
to completely correct, need ensure argument of type unsigned int
:
printf("%02x", (unsigned)arr[i]);
Comments
Post a Comment