本文介绍了C ++中的字节到字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正试图:
- 将一组8个整数(均值为0或1)转换为一个字节
- 反转该字节的位顺序
- 打印该字节的值(采用哪种格式?)(我可以猜测,直到在这里找到它为止)
此外,我不允许对此问题使用STL。
Also, I'm not allowed to use the STL for this problem.
推荐答案
因此,您想反转字节中的位。也就是说,这些位应该这样移动:
So, you want to reverse the bits in a byte. That is, the bits should move so:
from: 7 6 5 4 3 2 1 0
to: 0 1 2 3 4 5 6 7
此代码可以很好地做到这一点-您可以找到更好的算法如果您搜索。
This code will do it, inelegantly - you can find much better algorithms if you search. Can you see how it works though?
uint8_t reverse_bits(uint8_t byte)
{
return ((byte & 0x01) << 7)
|((byte & 0x02) << 5)
|((byte & 0x04) << 3)
|((byte & 0x08) << 1)
|((byte & 0x10) >> 1)
|((byte & 0x20) >> 3)
|((byte & 0x40) >> 5)
|((byte & 0x80) >> 7);
}
这篇关于C ++中的字节到字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!