C/C++ 中的位顺序

发布于 2024-12-06 21:57:45 字数 331 浏览 0 评论 0原文

我必须实现一个以 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自演自醉 2024-12-13 21:57:45

字节顺序取决于平台。无论如何,您不必担心实际的顺序,除非您正在序列化字节(您可能正在尝试这样做)。在这种情况下,您仍然不需要担心各个字节在机器上时如何存储,因为无论如何您都必须单独挖出这些位。幸运的是,如果与 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.

说不完的你爱 2024-12-13 21:57:45

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文