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

一个人想着一个人 提交于 2019-12-18 19:04:45

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/11193800/c-bit-operations-copy-one-bit-from-one-byte-to-another-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!