Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When printing hex values using %x why is 'ffffff' printed after each value? [duplicate]

Tags:

c++

In a sample c++ code I will open a file and print each char in hexa file has only 16 chars but why ffffff will print after each heax values?

char buff[256];
// buff filled with fread
for(i=0;i<16;i++)
printf("%x",buff[i]);

Output is:

4affffff67ffffffcdffffff

Why is this?

like image 331
Syedsma Avatar asked Sep 21 '11 08:09

Syedsma


1 Answers

Edit:

 printf("%x",  (int)(*(unsigned char*)(&buff[i])) );

This should make the trick. My first version was incorrect, sorry. The problem is in the sign bit: every value more than 127 was handled as negative. Casting to unsigned char should solve the problem.

like image 67
Alex F Avatar answered Sep 20 '22 05:09

Alex F