【发布时间】:2021-07-23 05:06:58
【问题描述】:
我的目标是将long 保存为四个字节like this:
unsigned char bytes[4];
unsigned long n = 123;
bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;
但我希望代码是可移植的,所以我使用来自<limits.h> 的CHAR_BIT:
unsigned char bytes[4];
unsigned long n = 123;
bytes[0] = (n >> (CHAR_BIT * 3)) & 0xFF;
bytes[1] = (n >> (CHAR_BIT * 2)) & 0xFF;
bytes[2] = (n >> CHAR_BIT) & 0xFF;
bytes[3] = n & 0xFF;
问题是位掩码0xFF只占8位,不一定等于1个字节。有没有办法让上层代码在所有平台上完全可移植?
【问题讨论】:
-
我想我遗漏了一些东西,但为什么第一个不便携?
-
@efox29 有些架构的字节大于 8 位。
-
此外,不能保证
long由4 个字节组成。所以你试图解决的任务是不可移植的:) -
很有趣……但这有什么关系吗?您将值存储在无符号字符(可能是也可能不是 8 位)中。为什么不使用 stdint.h 来获取指定大小的 uint8_t ?
-
解决问题的最佳方法是
_Static_assert(CHAR_BITS==8, "Don't import C libraries into your horrible exotic DSP project. And consider getting a better CPU.");