C/C++ 中的位顺序
我必须实现一个以 8 位字定义数据的协议,首先从最低有效位 (LSB) 开始。我想用 unsigned char
实现这些数据,但我不知道 C/C++ 中 LSB 和最高有效位 (MSB) 的位顺序是什么,这可能需要交换位。
谁能解释一下如何找出 unsigned char
是用 MSB-LSB 或 LSB-MSB 编码的?
示例:
unsigned char b = 1;
MSB-LSB: 0000 0001
LSB-MSB:1000 0000
I have to implement a protocol which defines data in 8bit words, which starts with the least significant bit (LSB) first. I want to realize this data with unsigned char
, but I don't know what's the bit order of LSB and most significant bit (MSB) in C/C++, that could possible require swapping the bits.
Can anybody explain me how to find out an unsigned char
is encoded: with MSB-LSB or LSB-MSB?
Example:
unsigned char b = 1;
MSB-LSB: 0000 0001
LSB-MSB: 1000 0000
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字节顺序取决于平台。无论如何,您不必担心实际的位顺序,除非您正在序列化字节(您可能正在尝试这样做)。在这种情况下,您仍然不需要担心各个字节在机器上时如何存储,因为无论如何您都必须单独挖出这些位。幸运的是,如果与 1 按位与,则无论存储顺序如何,您都会得到 LSB;与 2 进行位与,得到下一个最高有效位,依此类推。编译器将整理出在机器代码中生成哪些常量,以便抽象出该级别的详细信息。
Endian-ness is platform dependent. Anyway, you don't have to worry about actual bit order unless you are serializing the bytes, which you may be trying to do. In which case, you still don't need to worry about how individual bytes are stored while they're on the machine, since you will have to dig the bits out individually anyway. Fortunately, if you bitwise AND with 1, you get the LSB, regardless of storage order; bit-AND with 2 and you get the next most significant bit, and so on. The compiler will sort out what constants to generate in the machine code, so that level of detail is abstracted away.
C/C++中没有这样的东西。最低有效位是——好吧——最低有效位。由于这些位没有地址,因此没有其他排序。
There is no such thing in C/C++. The least significant bit is -- well -- the least significant bit. Since the bits don't have addresses, there is no other ordering.