How to get the value of individual bytes of a variable?

You have to know the number of bits (often 8) in each "byte". Then you can extract each byte in turn by ANDing the int with the appropriate mask. Imagine that an int is 32 bits, then to get 4 bytes out of the_int:

  int a = (the_int >> 24) & 0xff;  // high-order (leftmost) byte: bits 24-31
  int b = (the_int >> 16) & 0xff;  // next byte, counting from left: bits 16-23
  int c = (the_int >>  8) & 0xff;  // next byte, bits 8-15
  int d = the_int         & 0xff;  // low-order byte: bits 0-7

And there you have it: each byte is in the low-order 8 bits of a, b, c, and d.


You can get the bytes by using some pointer arithmetic:

int x = 12578329; // 0xBFEE19
for (size_t i = 0; i < sizeof(x); ++i) {
  // Convert to unsigned char* because a char is 1 byte in size.
  // That is guaranteed by the standard.
  // Note that is it NOT required to be 8 bits in size.
  unsigned char byte = *((unsigned char *)&x + i);
  printf("Byte %d = %u\n", i, (unsigned)byte);
}

On my machine (Intel x86-64), the output is:

Byte 0 = 25  // 0x19
Byte 1 = 238 // 0xEE
Byte 2 = 191 // 0xBF
Byte 3 = 0 // 0x00