A byte consists of 8 bits. Each byte can store a decimal value up to 255
or 11111111
in binary form.
Using these properties, we can develop a function that takes an integer input and converts the number into a specific byte array that represents the integer in binary form.
Before we jump into the code, it is important to understand how we can achieve a successful conversion.
Let’s start by assuming a byte array of size 4. Each index of this byte array contains 8 bits.
The entire byte array represents a single integer as a whole. We can consider the leftmost bit to be the Most Significant Bit (MSB) and the rightmost bit to be the Least Significant Bit (LSB).
To convert an integer to its binary representation, we use the right shift operator (>>
).
The right shift operator shifts the bits of the first operand by the number of places specified by the second operand. To put it simply, the right shift operator divides the first operand by 2 raised to the power of the second operand:
Let’s look at an example:
In the above example, we take the number 32 and shift it by 0
and 8
. We increment by 8 since each byte contains exactly 8 bits.
We obtain 32 and 0 as our answers.
&
operatorIn the previous example, we saw how to use the >>
operator to split the input into each byte of our array. However, we also need to ensure that each byte contains exactly 8 bits.
To do this, we use the bitwise AND operator (&
). We &
the value present in each byte by 0xFF
which is the hex (16 bit) notation for 255
. This way, we obtain the last 8 bits of our value.
Let’s look at an example:
#include <iostream>#include <stdio.h>#include <limits.h>using namespace std;void print(unsigned char byte){for (int i = 7; i >= 0; i--) {int b = byte >> i;if (b & 1)cout << "1";elsecout << "0";}}int main(){unsigned char bytes[4];unsigned long n = 5000;bytes[0] = (n >> 24) & 0xFF;bytes[1] = (n >> 16) & 0xFF;bytes[2] = (n >> 8) & 0xFF;bytes[3] = (n >> 0) & 0xFF;cout << "Integer: " << n << endl;cout << "Byte Array: ";for(int i = 0; i < 4; i++){print(bytes[i]);cout << "\t";}}
The above code represents the C++ algorithm for converting an integer into a byte array.
We define a byte array of size 4 (32 bits). We split the input integer (5000) into each byte by using the >>
operator. The second operand represents the lowest bit index for each byte in the array.
To obtain the 8 least significant bits for each byte, we &
the result with 0xFF
.
Finally, we print each byte using the print
function.
Free Resources