8

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?

Antonio Pérez
  • 6,702
  • 4
  • 36
  • 61
Syedsma
  • 1,183
  • 5
  • 17
  • 22
  • 3
    Show us the full code, specifically, what `buff` is and how it is filled with data. – orlp Sep 21 '11 at 08:25
  • 2
    For the love of bacon, _PLEASE_ don't add tags that do not apply to your question. You stated it is C++ code (though I'd argue it's really C code) but you added other languages... don't do that. – Jeff Mercado Sep 21 '11 at 08:25
  • Please label valid C code as such, and only as such. Other people browsing the site could otherwise think this is good/common/canonical/etc. C++ code. – PlasmaHH Sep 21 '11 at 10:26
  • See this [thread][1] [1]: http://stackoverflow.com/questions/479373/c-cout-hex-values –  Sep 21 '11 at 10:52
  • See this thread http://stackoverflow.com/questions/479373/c-cout-hex-values –  Sep 21 '11 at 10:55

2 Answers2

14

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.

Alex F
  • 42,307
  • 41
  • 144
  • 212
0
printf("%x", (unsigned int)(unsigned char)buff[i]);

Explanation:

printf will first convert char to int for you. If your char is signed (first bit is 1) - e.g. 10000001 - then sign extension will preserve the value when converting to int: 11111111 11111111 11111111 10000001. The fix is to convert it yourself first (without sign extension).

phuclv
  • 37,963
  • 15
  • 156
  • 475
Peter Tseng
  • 13,613
  • 4
  • 67
  • 57