c - Save int as a char? -


this question has answer here:

i'm trying save integer character.

char = 80; printf("0x%x", i); 

the above code displays 0x50 (1 byte). if value above 128, prints 4 byte value.

char = 130; printf("0x%x", i); // prints 0xffffff82 

how can store integer value 1 byte if value greater 128 (print 82 instead of ffffff82 in second example) ?

this expected behavior on systems char type signed: negative values of char sign-expanded size of int.

if print last 8 bits, mask 0xff, this:

printf("0x%x", & 0xff); // prints 80 

demo on ideone.

an alternative approach use unsigned char. avoid sign extension 8-bit numbers significant bit set 1.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -