1.判断当前CPU使用哪种C++ Endian?
2.如果当前数据的Endian和当前CPU相反,如何装换?
代码相当直观:
1.判断CPU的C++ Endian:
- union {
- short s;
- char c[sizeof(short)];
- } un;
- un.s = 0x0102;
- _isLittleEnd = (un.c[0] == 0x2);
最后的_isLittleEnd是一个bool变量用来保存判定的结果:
2.如何把一个相反C++ Endian的数据转换过来:
- void Helper::swap(char ch[], int count) {
- int size = count / 2;
- int max = count - 1;
- for (int i = 0; i < size; i++) {
- char t = ch[i];
- ch[i] = ch[max - i];
- ch[max - i] = t;
- }
其实是将char[]数组就地反转.
3.如何把short/int/double等数据反转过来呢:
以int 为例的代码如下:
- int Helper::swap(int data) {
- union {
- int _i;
- char _c[sizeof(int)];
- } un;
- un._i = data;
- swap(un._c, sizeof(int));
- return un._i;
- }