下面将大端点的byte设置为1,小端点的设置为0.
uint16_t word = 0x0001;
uint8_t byte = *(((uint8_t *)&word) + 1);有没有任何方法可以获得跨平台安全的低字节或高字节的地址?
发布于 2021-07-03 10:12:33
由于C99,代码可以使用复合文字来查找MSByte地址偏移量。
让编译器形成高效的代码。
下面使用一个4字节的例子来帮助演示如何使用大、小和PDP端。
int main() {
uint32_t word = 0x12345678;
printf("%p\n", (void*)&word);
for (unsigned i=0; i<sizeof word; i++) printf("%x\n", ((uint8_t*) &word)[i]);
uint8_t *msbyte_address = ((uint8_t*) &word) + //
// v----------------------------------------------------v compound literal
( union { uint32_t u32; uint8_t u8[4]; }) {0x00010203}.u8[0];
// value at 1st byte ^---^
printf("%p\n", (void*)msbyte_address);
}示例输出(小endian)
0xffffcbfc
78
56
34
12
0xffffcbff对于uint16_t
uint16_t word = 0x1234;
uint8_t *msbyte_address = ((uint8_t*) &word) +
( union { uint16_t u16; uint8_t u8[2]; }) {0x0001}.u8[0];发布于 2021-07-03 07:00:56
也许是这样的:
int isBigEndian()
{
uint16_t word = 0x0001;
return *(((uint8_t *)&word) + 1);
}
void main()
{
uint16_t word = 0x0001;
uint8_t byte = *(((uint8_t *)&word) + isBigEndian());
printf("%d\n", byte);
}为了避免每次运行时检查,您可以使用#define并验证它是使用assert的正确假设。如下所示:
#define BIG_ENDIAN 0 // 0 or 1 depending on what the platform is
void main()
{
assert(isBigEndian() == BIG_ENDIAN); // Make sure #define is OK
// more code...
}在代码的其他地方,根据平台的不同,使用符号BIG_ENDIAN编译代码。因此,除了assert之外,没有其他实际检查。
https://stackoverflow.com/questions/68233297
复制相似问题