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

拜拜、爱过 提交于 2019-11-30 17:38:00
emesx
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.

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