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?
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.