天天看點

16.3.1 位元組序 測試

16.3.1 位元組序
(1)概述
	1.位元組序是一個處理器架構特性,用于指定資料内部的位元組如何排序
	2.大段:像存儲字元串一樣,資料的高位元組存儲在記憶體的低位元組中。
	3.小端:與大段相反	
	4.有的作業系統既可以配置為大端,也可以配置為小端
	5.TCP/IP協定棧使用大端位元組序
(2)各平台的位元組序
	---------------------------
	作業系統		位元組序	
	---------------------------
	FreeBSD8.0		小端
	Linux3.2.0		小端
	Mac OS X10.6.8	小端
	Solaris 10		大端
	---------------------------
(3)處理器位元組序與網絡位元組序轉換
	uint32_t htonl(uint32_t hostint32);		// 傳回以網絡位元組序表示的32位整數
	uint16_t htons(uint16_t hostint16);		// 傳回以網絡位元組序表示的16位整數
	uint32_t ntohl(uint32_t netint32);		// 傳回以主機位元組序表示的32位整數
	uint16_t ntohs(uint16_t netint16);		// 傳回以主機位元組序表示的32位整數
           
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

/*
	測試目的: 測試系統的位元組序
	測試結果: sys use litter-endian
*/

int main(int argc, char **argv)
{
	int a = 0x12345678;
	char first = *((char *)&a);
	if (first == (char)0x12)
		printf("sys use big-endian\n");
	else if(first == (char)0x78)
		printf("sys use litter-endian\n");
	else
		printf("ERROR\n");
		
	return 0;
}

           

繼續閱讀