天天看點

位元組排序函數與位元組操縱函數位元組排序函數位元組操縱函數:

位元組排序函數

       考慮一個16bit的整數,它由2個位元組組成。記憶體中存儲這兩個位元組有兩種方法:一種是将低序位元組存儲在起始位置,這種稱為小端(little-endian)位元組序,另一種是将高序位元組存儲在起始位址,這稱為大端(bin-endian)位元組序。MSB(最高有效位):16位數的最左一位。LSB(最低有效位):最右一位。

檢視主機的位元組序:

#include<stdio.h>
#include<stdlib.h>
int main()
{
	union 
	{
		short s;
		char c[sizeof(s)];
	}un;
	un.s=0x0102;
	
	if(sizeof(short)==2)
	{
		if(un.c[0]==1&&un.c[1]==2)
			printf("big-endian\n");
		else if(un.c[0]==2&&un.c[1]==1)
			printf("little-endian");
		else
			printf("unknown\n");
	}
	else
		printf("szieof(short)=%d\n",sizeof(short));
	exit(0);
}
           

網絡位元組序采用大端位元組序,以下函數實作網絡位元組序與主機位元組序的轉換:

 #include <arpa/inet.h>

       uint32_t htonl(uint32_t hostlong);

       uint16_t htons(uint16_t hostshort);

       uint32_t ntohl(uint32_t netlong);

       uint16_t ntohs(uint16_t netshort);

位元組操縱函數:

源自4.3bsd套接字提供:

void bzero(void *s, size_t n);

void bcopy(const void *src, void *dest, size_t n);

int bcmp(const void *s1, const void *s2, size_t n);

源自ANSC C提供:

void *memset(void *s, int c, size_t n);

void *memcpy(void *dest, const void *src, size_t n);

int memcmp(const void *s1, const void *s2, size_t n);

繼續閱讀