Skip to content

Instantly share code, notes, and snippets.

@sotex
Created February 27, 2019 07:30
Show Gist options
  • Save sotex/3f82a7087082c8fa9c73f3764c8fb7a8 to your computer and use it in GitHub Desktop.
Save sotex/3f82a7087082c8fa9c73f3764c8fb7a8 to your computer and use it in GitHub Desktop.
编译期字节序判断.cpp
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// C++ 11支持强类型枚举和constexpr
enum EndianOrder : uint32_t{
ENDIAN_BIG = 0x00010203, /* 大端序 ABCD */
ENDIAN_LITTLE = 0x03020100, /* 小端序 DCBA */
ENDIAN_BIG_WORD = 0x02030001, /* 中端序 CDAB, Honeywell 316 风格 */
ENDIAN_LITTLE_WORD = 0x01000302 /* 中端序 BADC, PDP-11 风格 */
};
static constexpr uint8_t edvalx[4] = {0, 1, 2, 3};
union ED_TEST{
constexpr ED_TEST(uint32_t val):x(val){}
uint32_t x;
uint8_t edval[4];// = {0, 1, 2, 3};
};
static constexpr ED_TEST m(0x00010203); //= {0x00010203};//{0x00,0x01,0x02,0x03};
constexpr EndianOrder getEndianOrder()
{
return (EndianOrder)(*(uint32_t*)edvalx);
// return (0x00 == m.edval[0])?
// EndianOrder::ENDIAN_BIG:
// (0x03 == m.edval[0])?
// EndianOrder::ENDIAN_LITTLE:
// (0x02 == m.edval[0])?
// EndianOrder::ENDIAN_BIG_WORD:
// EndianOrder::ENDIAN_LITTLE_WORD;
//constexpr union{
// 上面枚举中的四个值,在它们对应的字节序中
// 值的内存布局应该与下面的edval一致
// uint8_t edval[4];// = {0, 1, 2, 3};
// uint32_t x;
//}m;
// switch(m.x){
// case 0x00010203:return EndianOrder::ENDIAN_BIG;
// case 0x03020100:return EndianOrder::ENDIAN_LITTLE;
// case 0x02030001:return EndianOrder::ENDIAN_BIG_WORD;
// case 0x01000302:return EndianOrder::ENDIAN_LITTLE_WORD;
// }
// return EndianOrder::ENDIAN_LITTLE;
//return (EndianOrder)m.x;
}
int main()
{
// 这两个宏是gcc或者clang支持的
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
puts("小端序");
#elif __BYTE_ORDER__== __ORDER_BIG_ENDIAN__
puts("大端序");
#else
puts("未知字节序");
#endif // __BYTE_ORDER__
constexpr EndianOrder ed = getEndianOrder();
static_assert(ed == EndianOrder::ENDIAN_BIG,"大端序");
static_assert(ed == EndianOrder::ENDIAN_LITTLE,"小端序");
static_assert(ed == EndianOrder::ENDIAN_BIG_WORD,"中大端序");
static_assert(ed == EndianOrder::ENDIAN_LITTLE_WORD,"中小端序");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment