When printing hex values ​​using% x, why does "ffffff" print after each value?

In the C ++ code example, I will open the file and print each char in hexadecimal format, the file has only 16 characters, but why will ffffff print after each heax value?

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

Exit:

 4affffff67ffffffcdffffff 

Why is this?

+6
source share
2 answers

Edit:

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

That should do the trick. My first version was wrong, sorry. The problem is the sign of the bit: each value greater than 127 has been treated as negative. To solve the problem, you need to solve the problem with

+12
source
 printf("%x", (unsigned int)(unsigned char)buff[i]); 

Explanation:

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

0
source

Source: https://habr.com/ru/post/897735/


All Articles