Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C print my hex values incorrectly?

Tags:

c

So I'm a bit of a newbie to C and I am curious to figure out why I am getting this unusual behavior.

I am reading a file 16 bits at a time and just printing them out as follows.

#include <stdio.h>

#define endian(hex) (((hex & 0x00ff) << 8) + ((hex & 0xff00) >> 8))

int main(int argc, char *argv[])
 {
  const int SIZE = 2;
  const int NMEMB = 1;
  FILE *ifp; //input file pointe
  FILE *ofp; // output file pointer

  int i;
  short hex;
  for (i = 2; i < argc; i++)
   {
    // Reads the header and stores the bits
    ifp = fopen(argv[i], "r");
    if (!ifp) return 1;
    while (fread(&hex, SIZE, NMEMB, ifp))
     {
      printf("\n%x", hex);
      printf("\n%x", endian(hex)); // this prints what I expect
      printf("\n%x", hex);
      hex = endian(hex);
      printf("\n%x", hex);
     }   
   }
 }

The results look something like this:

ffffdeca
cade // expected
ffffdeca
ffffcade
0
0 // expected
0
0
600
6 // expected
600
6

Can anyone explain to me why the last line in each block doesn't print the same value as the second?

like image 850
Ceasar Bautista Avatar asked Dec 09 '11 04:12

Ceasar Bautista


People also ask

How do I print hex data?

Printing the number in Hexadecimal format To print integer number in Hexadecimal format, "%x" or "%X" is used as format specifier in printf() statement. "%x" prints the value in Hexadecimal format with alphabets in lowercase (a-f). "%X" prints the value in Hexadecimal format with alphabets in uppercase (A-F).

What format specifier should be used to print a hex value?

The %x %X format specifiers: The %x or %X format specifier is used to represent the integer Hexadecimal value. %x displays the hexadecimal values with lowercase alphabets whereas the %X specifier displays the hexadecimal values with uppercase alphabets.

What does printf actually do?

The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.


1 Answers

The placeholder %x in the format string interprets the corresponding parameter as unsigned int.

To print the parameter as short, add a length modifier h to the placeholder:

printf("%hx", hex);

http://en.wikipedia.org/wiki/Printf_format_string#Format_placeholders

like image 129
timothyqiu Avatar answered Sep 23 '22 20:09

timothyqiu