I am trying to split binary (for example 0100 0101 0100 0001
) into binaries with 6 bit size (get 0100
, 010101
, 000001
, ) and also add to them two binaries (add 10
to 000001
=> 10000001
).
How can I do this in C?
CodePudding user response:
You are looking for bitwise operators
A few examples, with the mandatory 0b
at the beginning of binary literals:
0b0100010101000001 & 0b111111;// = 0b000001
0b0100010101000001 & (0b111111 << 6);// = 0b010101
0b0100010101000001 & (0b111111 << 12);// = 0b010001
0b101010 | 0b10 << 6;// = 0b10101010
Note: Depending on the compiler you are using, writing binary literals as 0bxxxx
may not be valid, as it is not standard. You may have to convert to decimal or hex (0xAF
). See this post.
CodePudding user response:
You can use a combination of bit masks and bit shifts to extract portions of your source, and to modify the value after the extraction.
To isolate the least significant ('lowest') 6 bits from a source, mask that with binary 00111111 (hex 3F) using the bitwise AND (&
) operator; to add the required "10" bits as the most significant ('highest') 2 bits, mask with binary 10000000 (hex 80) using the bitwise (inclusive) OR (|
) operator.
For an unsigned source integer, you can perform the above operations sequentially, right-shifting by 6 bits (using the >>
or >>=
operator) after each extraction, until all required fields are extracted.
Taking your source as an unsigned short
and your required destination as an array of 3 unsigned char
, the following illustrates the process:
#include <stdio.h>
void splitbyte(unsigned short src, unsigned char dst[3])
{
for (int i = 0; i < 3; i) {
dst[i] = (src & 0x3F) | 0x80; // Extract the low 6 bits and mask in the top "10! bits
src >>= 6; // Shift right by 6, so next loop extracts next field
}
}
int main(void)
{
unsigned short src = 0x4541; // 0100 0101 0100 0001
unsigned char dst[3];
splitbyte(src, dst);
// You could printf in a loop but I wanted to comment each value ...
printf("X\n", (unsigned)(dst[0])); // 81 = 10 000001
printf("X\n", (unsigned)(dst[1])); // 95 = 10 010101
printf("X\n", (unsigned)(dst[2])); // 84 = 10 000100
return 0;
}