How to convert an int to two bytes in C/C++?


I get data from a temperature sensor on a microcontroller that has a 10-bit AD converter. I store the data in a variable of type int (32 bits), and I need to send this data via serial communication. For this, I need to convert this int value to byte type, but since they are 10 bits if I convert to just one byte I will lose information, so I need to convert the int to two bytes so that I can transmit one byte at a time by serial port. I will also need to convert these two bytes to an integer value again.

How do I convert an int to two bytes and two bytes to an int again using C/C++ ?


Something we have to clear up first is that the int type on modern platforms is 4 bytes long . That's a problem because it 's impossible to make 4 bytes fit into 2 bytes , isn't it?!

On the other hand, the short int type is guaranteed to occupy at least 2 bytes on any platform. These statements can be easily verified using sizeof() , which returns the number of bytes that a given data type occupies:

printf("%d\n", sizeof(int));
printf("%d\n", sizeof(short int));

So, this answer assumes that you would like to separate each byte of a short int variable .

To accomplish this, we use a bit mask , which involves applying operations binary logic (bitwise operations) and bit shift (bit shift) to extract the 8 bits of interest in 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 decimal base is represented by 1010 0101 0110 1001 in binary base system. It is relevant to know this because after the separation takes place, we will have an unsigned char variable to store the first byte –> 0110 1001 (105), and another unsigned char variable to store the second byte –> 1010 0101 (165).

To extract the first byte from num :

unsigned char byte1 = (num & 255);          // Ou: (num & 0xFF)
printf("%d\n\n", byte1);

To extract the second byte from 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 bitmasks 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 how bit masks work.

Good luck!

Scroll to Top