Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

byte

I know that to get the number of bytes used by a variable type, you use sizeof(int) for instance. How do you get the value of the individual bytes used when you store a number with that variable type? (i.e. int x = 125.)

like image 868
Tobey Avatar asked Dec 30 '11 14:12

Tobey


People also ask

How do you find the value of bytes?

1 byte = 8 bits = 28 = 256 values A byte could look as follows: 00111001. If you imagine the bit as a binary letter, then a byte is the smallest possible word. It takes 1 byte to represent an actual letter or number.

How many bytes are in each variable?

Variable Types Character variables hold a single byte representing 1 of the 256 characters and symbols in the standard ASCII character set.

Why is a byte 255 and not 256?

A byte has only 8 bits. A bit is a binary digit. So a byte can hold 2 (binary) ^ 8 numbers ranging from 0 to 2^8-1 = 255. It's the same as asking why a 3 digit decimal number can represent values 0 through 999, which is answered in the same manner (10^3 - 1).

How many bytes is a number?

Whole numbers (integers) are usually represented with 4 bytes, or 32 bits. In the past, symbols (e.g., letters, digits) were represented with one byte (8 bits), with each symbol being mapped to a number between 0-255. The ASCII table provides the mapping.


2 Answers

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.

like image 159
Pete Wilson Avatar answered Oct 11 '22 10:10

Pete Wilson


You could make use of a union but keep in mind that the byte ordering is processor dependent and is called Endianness http://en.wikipedia.org/wiki/Endianness

#include <stdio.h>
#include <stdint.h>

union my_int {
   int val;
   uint8_t bytes[sizeof(int)];
};

int main(int argc, char** argv) {
   union my_int mi;
   int idx;

   mi.val = 128;

   for (idx = 0; idx < sizeof(int); idx++)
        printf("byte %d = %hhu\n", idx, mi.bytes[idx]);

   return 0;
}
like image 38
DipSwitch Avatar answered Oct 11 '22 11:10

DipSwitch