One thing we have to clear up first is that the guy int
on the modern platforms has 4 bytes. That’s a problem because it is impossible to make 4 bytes fit within 2 bytes, it’s not true?!
On the other hand, there is the ensures that the type short int
occupies at least 2 bytes on any platform. These statements can be easily verified by sizeof()
, which returns the amount of bytes that a given data type occupies:
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(short int));
This way, this answer assumes that you would like to separate each byte from a variable short int
.
To accomplish this task, we can use a bit mask, which involves the application of binary logic (bitwise Operations) and bit displacement (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
on the decimal basis 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 variable unsigned char
to store the first byte --> 0110 1001
(105), and another variable unsigned char
to store the second byte --> 1010 0101
(165).
To extract the first byte of num
:
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 bit masks work, but to demonstrate how the problem could be solved in this way. There are over a hundred programming books and many more online records that describe in detail the operation of bit masks.
Good luck!
Try to be a little more explicit. When you say int you mean 32 bits? And when it says convert to 2 bytes it is to convert to a short int of 16 bits?
– user4552
I made some edits in my question. But the int is 32 bits and the two bytes are separated, because I need to byte by byte by serial port.
– Avelino
int
on the most modern platforms has 4 bytes. And 4 bytes do not fit within 2 bytes, unfortunately. But if you are talking aboutshort int
there yes to divide it into separate bytes. ;D– karlphillip
The AD converter stores the information in 10 bits. I am storing it in an int of 32, but it could be stored in a short. But the most significant part is all zeroed since the values go from 0 to 1023 only. However, I cannot send an int, I need to send the data byte by byte, so I need to divide this int into 2 bytes (with the least significant part) where the values from 0 to 1023 will be.
– Avelino
@Avelino If you need to do the reverse operation, let me know that I update the response.
– karlphillip