-1

I'm attempting to write a program in C that examines bytes in memory and prints their contents. Given a 4-byte unsigned integer, what would a function look like that prints a specific byte of the integer to stdout in hexadecimal? Does printf have some sort of capability like this built-in?

Here's the interface of what I'm looking for.

// number - the integer to be examined
// order - the byte to be examined, with 0 being the lowest-order
//         (first) byte and 3 being the highest order (last) byte
void print_byte(unsigned number, unsigned order);

If it's important for the implementation, this would be a little-endian machine.

Jared
  • 4,240
  • 4
  • 22
  • 27
  • `printf("%hhX", number >> (order * 8));` might be a start. – chux - Reinstate Monica Jan 28 '15 at 05:11
  • Posting some code for us to complement on & correct would be a better start ;-) – Mawg says reinstate Monica Jan 28 '15 at 09:15
  • @phadej Disagree that this is a close match to the posted duplicate. The purported duplicate show how to extract from an integer to integer. This post needs asks how to "print" a specific byte. Certainly code could use the duplicate and then print the result, but tighter methods could exists by-passing the integer to integer conversion as suggested in my above comment. – chux - Reinstate Monica Jan 28 '15 at 16:14
  • @Mawg Sorry, there really isn't any code. I always post some snippet if I can. I'm asking for something that I would assume to be a one-line thing considering C is good for dealing with individual bytes. This just isn't something that would be easily found in common textbooks is why I decided to ask here. – Jared Jan 28 '15 at 18:31

2 Answers2

0

Please Try This...

#include <stdio.h>
void print_byte(unsigned number, unsigned order)
{
    unsigned i = 0;

    i = (number >> (8*order)) & 0x000000FF;

    printf("Number:0x%08x, Byte:%02x, Order:%d\n",number,i,order);

    return;
}

int main(void) {

    print_byte(0x1f2e3d4c,0);
    print_byte(0x1f2e3d4c,1);
    print_byte(0x1f2e3d4c,2);
    print_byte(0x1f2e3d4c,3);

    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jjm
  • 431
  • 3
  • 19
0

If using C99 or later, use the length modifier "hh" after shifting. This modifier will convert the integer to unsigned/signed char before printing. Use 8 or CHAR_BIT depending on meaning of "byte".

printf("%hhX", number >> (order * 8));

or

#include <limits.h>
printf("%hhX", number >> (order * CHAR_BIT));
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256