Something we have to clarify before is that the type int
on modern platforms has 4 bytes . This is a problem because it is impossible to make 4 bytes fit within 2 bytes , is not it?!
On the other hand, there is a guarantee that type short int
occupies at least 2 bytes on any platform. These statements can be easily verified by sizeof()
, which returns the number of bytes that a given type of data occupies:
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(short int));
In this way, this answer assumes that you would like to separate each byte of a variable short int
.
To perform this task, we can use a bit mask , which involves the implementation of operations of binary logic ( bitwise operations ) and bit shift ) to extract the 8 bits that interest us from the original variable.
To begin this task, we declare and initialize an appropriate variable:
short int num = 42345;
It is interesting to note that the number 42345
in the decimal base is represented by 1010 0101 0110 1001
in the binary base system. It is relevant to know this because after the separation occurs, we will have a unsigned char
variable to store the first byte - > % with% (105), and another variable 0110 1001
to store the second byte - > unsigned char
(165).
To extract the first byte of 1010 0101
:
unsigned char byte1 = (num & 255); // Ou: (num & 0xFF)
printf("%d\n\n", byte1);
To extract the second byte of num
:
unsigned char byte2 = ((num >> 8) & 255); // Ou: ((num >> 8) & 0xFF);
printf("%d\n", byte2);
The purpose of the answer is not to discuss how masks work, but to demonstrate how the problem could be solved in this way. There are more than a hundred programming books and many more online logs that describe in detail the operation of bitmasks.
Good luck!