转贴地址:http://www.chinaunix.net/jh/23/823662.htmlphp
#######################
html
//声明: 1 本帖做者是:converse ,至此感谢!编程
2 红色背景字体为本人添加内容!
网络
3 黄色背景为我的阅读重点!
字体
#######################
ui
little endian和big endian是表示计算机字节顺序的两种格式,所谓的字节顺序指的是长度跨越多个字节的数据的存放形式.
spa
简单的说,little endian把低字节存放在内存的低位;而big endian将低字节存放在内存的高位.
.net
低 0x0000000 cd 12 12 高位
unix
| 0x0000001 ab 34 34 |
code
∨ 0x0000002 34 ab ab ∨
如今主流的CPU,intel系列的是采用的little endian的格式存放数据,而motorola系列的CPU采用的是big endian.
/******************************************************************** created: 2006-9-5 filename: test.cpp author: 李创 purpose: 可移植的用于判断存储格式是 little endian仍是big ednian的C代码 取自<<C: A Reference Manual>> *********************************************************************/ #include <stdio.h> union { long Long; char Char[sizeof(long)]; }u; int main() { u.Long = 1; if (u.Char[0] == 1) { printf("Little Endian!\n"); } else if (u.Char[sizeof(long) - 1] == 1) { printf("Big Endian!\n"); } else { printf("Unknown Addressing!\n"); } printf("Now, Let's look at every byte in the memory!\n"); for (int i = 0; i < sizeof(long); ++i) { printf("[%x] = %x\n", &u.Char, u.Char); } return 0; }
/******************************************************************** created: 2006-9-5 filename: get32put32.cpp author: 李创 purpose: 在little endian和big ednian之间相互转化数据的演示代码 *********************************************************************/ #include <stdio.h> const unsigned char SIZE_OF_UNSIGNEDINT = sizeof(unsigned int); const unsigned char SIZE_OF_UNSIGNEDCHAR = sizeof(unsigned char); void put_32(unsigned char *cmd, unsigned int data) { int i; for (i = SIZE_OF_UNSIGNEDINT - 1; i >= 0; --i) { cmd = data % 256; // 或者能够: //cmd = data & 0xFF; data = data >> 8; } } unsigned int get_32(unsigned char *cmd) { unsigned int ret; int i; for (ret = 0, i = SIZE_OF_UNSIGNEDINT - 1; i >= 0; --i) { ret = ret << 8; ret |= cmd; } return ret; } int main(void) { unsigned char cmd[SIZE_OF_UNSIGNEDINT]; unsigned int data, ret; unsigned char *p; int i; data = 0x12345678; printf("data = %x\n", data); // 以字节为单位打印出数据 p = (unsigned char*)(&data); for (i = 0; i < SIZE_OF_UNSIGNEDINT; ++i) { printf("%x", *p++); } printf("\n"); // 以相反的顺序存放到cmd之中 put_32(cmd, data); for (i = 0; i < SIZE_OF_UNSIGNEDINT; ++i) { printf("cmd[%d] = %x\n", i, cmd); } // 再以相反的顺序保存数据到ret中 // 保存以后的ret数值应该与data相同 ret = get_32(cmd); printf("ret = %x\n", ret); p = (unsigned char*)(&ret); for (i = 0; i < SIZE_OF_UNSIGNEDINT; ++i) { printf("%x", *p++); } printf("\n"); return 0; }