| 型別 | 32-bit (x86) | 64-bit (x86-64) | 應對 |
|---|---|---|---|
int | 4 | 4 | 用 sizeof(int) 而非寫死 4 |
long | 4 | 4/8 (LP64/LLP64) | 避免直接用 long,改用定長型別 |
void* | 4 | 8 | 用 sizeof(void*) 或 uintptr_t |
size_t | 4 | 8 | 標準庫保證足夠大 |
定長型別:int32_t, int64_t, intptr_t (C99 <stdint.h> / C++11 <cstdint>),或 Boost/ACE 對應型別。
0x01020304 記憶體序 04 03 02 01。01 02 03 04。網路/檔案傳輸鐵律:
// 主機序 ↔ 網路序 (大端)
uint32_t htonl(uint32_t host); // host to network long
uint32_t ntohl(uint32_t net); // network to host long
uint16_t htons(uint16_t host);
uint16_t ntohs(uint16_t net);
二進制檔案格式明確定義位元組序 (通常採網路序),讀寫時轉換。
offsetof、結構體大小等具體值。sizeof(T) 計算大小,alignof(T) (C++11) 查詢對齊需求。#pragma pack(n) 非標準,僅在特定編譯器支援下謹慎使用。uint32_t) 再操作。sizeof 或定長型別?uintptr_t/intptr_t?sizeof?