C - Printing out a char pointer in hex is giving me strange results -
so writing small , simple program takes number input, converts hex, , prints out 2 characters @ time.
for numbers, prints out ffffff in front of output.
this code:
//convert input unsigned int unsigned int = strtoul (argv[1], null, 0); //convert unsigned int char pointer char* c = (char*) &a; //print out char 2 @ time for(int = 0; < 4; i++){ printf("%02x ", c[i]); }
most of output fine , looks this:
./hex_int 1 01 00 00 00
but numbers output looks this:
./hex_int 100000 ffffffa0 ffffff86 01 00
if remove f's conversion correct, cannot figure out why doing on inputs.
anyone have ideas?
you're mismatching parameters , print formats. default argument promotions cause char
parameter (c[i]
) promoted int
, sign extends (apparently char
signed type). told printf
interpret argument unsigned int
using %x
format. boom - undefined behaviour.
use:
printf("%02x ", (unsigned int)(unsigned char)c[i]);
instead.
Comments
Post a Comment