cbit-manipulation

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;
}

Solution

  • byte_2 = (byte_2 & 0b01111111) | (byte_1 & 0b10000000);