Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C bit operations / copy one bit from one byte to another byte

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;
}
like image 436
astropanic Avatar asked Jun 25 '12 17:06

astropanic


People also ask

Can C manipulate bits?

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.

What is << in bit manipulation?

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.

Is bit manipulation fast?

On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition.

How do you flip a specific bit?

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


2 Answers

byte_2 = (byte_2 & 0b01111111) | (byte_1 & 0b10000000);
like image 130
emesx Avatar answered Sep 21 '22 14:09

emesx


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.

like image 27
Shahbaz Avatar answered Sep 20 '22 14:09

Shahbaz