Why does printing char sometimes print 4 bytes number in C -
why printing hex representation of char screen using printf prints 4 byte number?
this code have written
#include <stdio.h> #include <stdint.h> #include<stdio.h> int main(void) { char teststream[8] = {'a', 'b', 'c', 'd', 0x3f, 0x9d, 0xf3, 0xb6}; int i; for(i=0;i<8;i++){ printf("%c = 0x%x, ", teststream[i], teststream[i]); } return 0; }
and following output:
a = 0x61, b = 0x62, c = 0x63, d = 0x64, ? = 0x3f, � = 0xffffff9d, � = 0xfffffff3, � = 0xffffffb6
char
appears signed on system. standard "two's complement" representation of integers, having significant bit set means negative number.
in order pass char
vararg function printf
has expanded int
. preserve value sign bit copied new bits (0x9d
→ 0xffffff9d
). %x
conversion expects , prints unsigned int
, see set bits in negative number rather minus sign.
if don't want this, have either use unsigned char
or cast unsigned char
when passing printf
. unsigned char
has no bits compared signed char
, therefore same bit pattern. when unsigned value gets extended, new bits zeros , expected in first place.
Comments
Post a Comment