2

Possible Duplicate:
Print an int in binary representation using C

How would I print the byte representations of a short int, and double in C.

As in lets say I have a function display_shortInt, how would I make it print the byte representation of a short int? I'm new to C, thanks you!

Community
  • 1
  • 1
sebi
  • 815
  • 7
  • 15
  • 26

3 Answers3

7

What about this?

void print_bytes(void *p, size_t len)
{
    size_t i;
    printf("(");
    for (i = 0; i < len; ++i)
        printf("%02X", ((unsigned char*)p)[i]);
    printf(")");
}

void print_short(short x)
{
    print_bytes(&x, sizeof(x));
}

void print_double(double x)
{
    print_bytes(&x, sizeof(x));
}
//etc.

That will print the bytes that form the value, in hexadecimal, two characters per byte.

For example, in a little-endian machine, print_short(42) will print (2A00). In a big-endian machine it will be (002A).

rodrigo
  • 94,151
  • 12
  • 143
  • 190
2

There is no direct way (i.e. using printf or another standard library function) to print it. You will have to write your own function.

void printbits(unsigned int v) {
   for (; v; v >>= 1) 
      putchar('0' + (v & 1));
}
Rami Jarrar
  • 4,523
  • 7
  • 36
  • 52
2

If you want to see how it is organised in memory (architecture-dependent):

short val = 0x1234;
printf( "%02x%02x", ((char*)&val)[0], ((char*)&val)[1] );

If you just want to see how it is written (big-endian):

printf( "%04x", val );
paddy
  • 60,864
  • 6
  • 61
  • 103
  • 1
    But note that if `char` is signed (and it is in many architectures), and the byte if greater than 0x80, you will get some funny values. – rodrigo Sep 12 '12 at 07:55