vs c ++ cross endian union

时间:2012-11-09 11:34:39

标签: c++ endianness

  

可能重复:
  Any way to read big endian data with little endian program?

我在我的项目中有下面的union结构,我正在尝试修改它来读取一个大的endian文件,并且当程序在x86上运行时,它尝试将文件读取为little endian并从union返回错误的结果。有没有办法修改联合以大端格式读取它?或另一种获取正确数据类型的方法?

struct AptConstItem {
    AptConstItemType type;
    union {
        const char *strvalue;
        unsigned int numvalue;
    };
};

感谢。

1 个答案:

答案 0 :(得分:2)

无论字节顺序如何,您都使用相同的基本技术:阅读 大端:

uint32_t
readBigEndian( std::istream& binaryInput )
{
    uint32_t result 
            = (binaryInput.get() << 24) & 0xFF000000;
    result |= (binaryInput.get() << 16) & 0x00FF0000;
    result |= (binaryInput.get() <<  8) & 0x0000FF00;
    result |= (binaryInput.get()      ) & 0x000000FF;
    return result;
}

对于小端,你只需要改变班次和面具的顺序。