联盟黑客为端测试和字节交换 [英] Union hack for endian testing and byte swapping

查看:101
本文介绍了联盟黑客为端测试和字节交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关工会,写入一个成员和阅读其他成员(除字符数组)是UB。

For a union, writing to one member and reading from other member (except for char array) is UB.

//snippet 1(testing for endianess): 

union
{
    int  i;
    char c[sizeof(int)];
} x;

x.i = 1;                     // writing to i
if(x.c[0] == 1)              // reading from c[0]
{   printf("little-endian\n");
}
else
{   printf("big-endian\n");
}

//snippet 2(swap bytes using union):

int swapbytes()
{
    union                   // assuming 32bit, sizeof(int)==4
    {        
        int  i;
        char c[sizeof(int)];
    } x;
    x.i = 0x12345678;       // writing to member i
    SWAP(x.ch[0],x.ch[3]);  // writing to char array elements
    SWAP(x.ch[1],x.ch[2]);  // writing to char array elements
    return x.i;             // reading from x.i 
}   

1片段是合法的C或C ++而不是片段2.我是否正确?有人点标准的部分,在那里它说,它可以OK写信给工会会员,并从另一个成员是一个字符数组阅读。

Snippet 1 is legal C or C++ but not snippet 2. Am I correct? Can some one point to the section of standard where it says its OK to write to a member of union and read from another member which is a char array.

推荐答案

我相信它(片段1)在技术上的不可以允许的,但大多数编译器允许也无妨,因为人们使用这种$ C的$ C。 GCC即使它支持的文件。

I believe it (snippet 1) is technically not allowed, but most compilers allow it anyway because people use this kind of code. GCC even documents that it is supported.

您的有一些机器的问题是sizeof(int)的== 1,可能在某些既不是大尾数也不小尾数。

You will have problems on some machines where sizeof(int) == 1, and possibly on some that are neither big endian nor little endian.

要么使用会改变的话正确的顺序,或设置这个具有配置宏可用的功能。你可能需要认识到编译器和OS无妨。

Either use available functions that change words to the proper order, or set this with a configuration macro. You probably need to recognize compiler and OS anyway.

这篇关于联盟黑客为端测试和字节交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆