I know how to set a bit, clear a bit , toggle a bit, and check if a bit is set.
But, how I can copy bit, for example nr 7 of byte_1 to bit nr 7 in byte_2 ?
It is possible without an if statement (without checking the value of the bit) ?
#include <stdio.h>
#include <stdint.h>
int main(){
int byte_1 = 0b00001111;
int byte_2 = 0b01010101;
byte_2 = // what's next ?
return 0;
}
Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a byte. C language is very efficient in manipulating bits.
Left Shift ( << ): Left shift operator is a binary operator which shift the some number of bits, in the given bit pattern, to the left and append 0 at the end.
On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition.
To flip one or more bits, use binary XOR. In your case, the appropriate XOR mask is 1 shifted k bits to the left. is valid in C, Java, Python and a few other languages (provided the variables are appropriately defined).
byte_2 = (byte_2 & 0b01111111) | (byte_1 & 0b10000000);
You need to first read the bit from byte1
, clear the bit on byte2
and or
the bit you read earlier:
read_from = 3; // read bit 3
write_to = 5; // write to bit 5
the_bit = ((byte1 >> read_from) & 1) << write_to;
byte2 &= ~(1 << write_to);
byte2 |= the_bit;
Note that the formula in the other answer (if you extend it to using variables, instead of just bit 7) is for the case where read_from
and write_to
are the same value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With