Dev Notes

Software Development Resources by David Egan.

Convert an Array of Unsigned Chars to an int32_t Value


C, C++
David Egan

In C or C++, an array of four unsigned char values (four raw bytes) can be converted to a single int32_t value using bitwise operations.

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

int main()
{
	// An array of raw bytes
	unsigned char raw[] = {0xde, 0xad, 0xbe, 0xef};
	for (size_t i = 0; i < 4; i++) {
		printf("%d\n", raw[i]);
	}

	// To pack into a 4 byte data type, shift each element the 
	// appropriate number of bits and perform bitwise OR on
	// all shifted elements.
	uint32_t result = (raw[0] << 24 | raw[1] << 16 | raw[2] << 8 | raw[3]);

	printf("%%u result = %u\n", result); // 3735928559
	return 0;
}

Explanation

An array of unsigned char containing the decimal values 222, 173, 190, 239 can represented in binary format:

Decimal Binary
222 11011110
173 10101101
190 10111110
239 11101111

To get these values packed into a 4 byte data type such as uint32_t, the first (single byte) value in the array should be inserted into the most significant byte. The second should be inserted into the next most significant byte, and so on.

This can be achieved by:

  1. Bit shifting each byte to it’s required position
  2. Performing a bitwise OR operation on all bytes

Using the values from the above example:

# 11011110 << 24
+-----------------+-----------------+-----------------+-----------------+
| 1 1 0 1 1 1 1 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 |
+-----------------+-----------------+-----------------+-----------------+

# 10101101 << 16
+-----------------+-----------------+-----------------+-----------------+
| 0 0 0 0 0 0 0 0 | 1 0 1 0 1 1 0 1 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 |
+-----------------+-----------------+-----------------+-----------------+

# 10111110 << 8
+-----------------+-----------------+-----------------+-----------------+
| 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 1 0 1 1 1 1 1 0 | 0 0 0 0 0 0 0 0 |
+-----------------+-----------------+-----------------+-----------------+

# The least significant byte doesn't need shifting
+-----------------+-----------------+-----------------+-----------------+
| 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 0 0 0 0 0 0 0 0 | 1 1 1 0 1 1 1 1 |
+-----------------+-----------------+-----------------+-----------------+

Perform bitwise OR on all the above values:
+-----------------+-----------------+-----------------+-----------------+
| 1 1 0 1 1 1 1 0 | 1 0 1 0 1 1 0 1 | 1 0 1 1 1 1 1 0 | 1 1 1 0 1 1 1 1 |
+-----------------+-----------------+-----------------+-----------------+

References

Integers in C


comments powered by Disqus