简单的来说,通俗理解:
比如数据0x12345678
大端:地址由低到高,先放数据的高位,就是0x12,0x34,0x56,0x78;
小端:地址由低到高,先放数据的低位,就是0x78,0x56,0x34,0x12;
以下是验证代码(Windows、Linux均能跑通)
Windows平台需要在第一行加上#include “stdafx.h”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
#include <stdio.h> #include <string.h> union Int { char c[4]; int y; }; union Long { #ifdef _WIN32 char c[4]; #else char c[8]; #endif // _WIN32 long y; }; union LongLong { char c[8]; long long y; }; template<typename T> void Print(T& f) { unsigned char* p = (unsigned char*)&f; for (size_t i = 0; i < sizeof(T); ++i) { printf("%p %02x\n", p + i, *(p + i)); } printf("\n\n"); } int main() { printf("int: %lu\n", sizeof(int)); printf("long: %lu\n", sizeof(long)); printf("long long: %lu\n", sizeof(long long)); Int a; Long b; LongLong c; memset(&a, 0, sizeof(a)); memset(&b, 0, sizeof(b)); memset(&c, 0, sizeof(c)); a.y = 0x01234567; #ifdef _WIN32 b.y = 0x89abcdef; #else b.y = 0x0123456789abcdef; #endif // _WIN32 c.y = 0x1122334455667788; printf("Int: %p\n", &a); printf("Long: %p\n", &b); printf("LongLong: %p\n", &c); Print(a); Print(b); Print(c); return 0; } |
发表评论
要发表评论,您必须先登录。