大小端识别代码
给出系统大小端识别的代码,仅供参考。
传统写法:
- int get_order()
- {
- union endian
- {
- short s;
- char c[2];
- } order;
- order.s = 0x1234;
- if (order.c[0] == 0x12 && order.c[1] == 0x34)
- {
- return 1; /* big endian */
- }
- else
- {
- return 0; /* little endian */
- }
- }
简单写法:
- int get_order()
- {
- short s = 1;
- short *ps = &s
- char *pc;
- pc = (char *)ps;
- if (*pc == 0)
- {
- return 1; /* big endian */
- }
- else
- {
- return 0; /* little endian */
- }
- }
- static int test_order(char *c)
- {
- *c = 1;
- return 0;
- }
- int get_order()
- {
- int i = 0;
- test_order(&i);
- if (i == 0)
- {
- return 1; /* big endian */
- }
- else
- {
- return 0; /* little endian */
- }
- }
偷懒写法:
- int get_order()
- {
- if (htons(1) == 1)
- {
- return 1; /* big endian */
- }
- else
- {
- return 0; /* little endian */
- }
- }