c - How to print Bytes in order in a endian-portable way? -
c - How to print Bytes in order in a endian-portable way? -
i used simple function extensively in multi-threaded program:
char *serial2string(char *serial) { static char str[length * 2 + 1]; sprintf(str, "%08x%08x", ntohl(*(uint32_t *)(&serial[0])), ntohl(*(uint32_t *)(&serial[length / 2]))); homecoming str; }
i phone call different thread context, , static variable not protected against concurrency. bug happen sooner or later... created function simplify code needed, created concurrency issue. looking way either:
have function concurrent-safe. holding mutex work. create code uglier/heavier already. have macro or one-liner doing same thing simple plenty copy/paste everywhere need it. inlining works believe there better way.in other words, how can print length
bytes in order portable way (from endianness point of view) in thread-safe way?
edit phone call straight in printf
statement:
printf("error: no such device, serial:%s\n", serial2string(&buf[1]));
i see couple of options.
allocate string within function malloc:
const char *str = serial2string(serial); // utilize string, free when you're done free(str);
alternatively, create caller pass in memory string:
char str[256]; str = serial2string(serial, str, 256);
if utilize exclusively within printf, following:
#define serial_format "%08x%08x" #define serial2str(s) ntohl(*(uint32_t *)(&s[0])), ntohl(*(uint32_t *)(&s[length / 2])) printf("the serial is:" serial_format "\n", serial2str(serial));
c linux endianness
Comments
Post a Comment