14

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;
}
astropanic
  • 10,800
  • 19
  • 72
  • 132
  • Are you looking for how to do it in one operation? If not, you do what you already know how to do: check the bit in byte1, check the bit in byte2, if they aren't the same, set the bit in byte2. – Corey Ogburn Jun 25 '12 at 17:03
  • it must not be in one operation, but I want avoid checking prior the bit value (if it is possible) – astropanic Jun 25 '12 at 17:13
  • possible duplicate of [Setting a bit of an unsigned char with the another bit of another unsigned char without conditional](http://stackoverflow.com/questions/11170740/setting-a-bit-of-an-unsigned-char-with-the-another-bit-of-another-unsigned-char) – Heisenbug Jun 25 '12 at 19:33

2 Answers2

25
byte_2 = (byte_2 & 0b01111111) | (byte_1 & 0b10000000);
Eitan T
  • 32,660
  • 14
  • 72
  • 109
emesx
  • 12,555
  • 10
  • 58
  • 91
  • @EitanT The right & causes the entire right side to be 0 in that case. The left & clears the 7th bit. When you or them, it stays 0... – dcpomero Jun 25 '12 at 17:14
8

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.

Shahbaz
  • 46,337
  • 19
  • 116
  • 182