网络编程高低字节颠倒

接收一堆数,有些需要颠倒字节,比如

U8  jieshou_data[1000];

收到的数扔到这个数组里,但是里面有些数需要颠倒后,再给应用使用。

查查网上:

http://www.360doc.com/content/14/1113/16/16170632_424843985.shtml

http://blog.sina.com.cn/s/blog_b87e685b0102wcsq.html

short型:

unsigned short swapShort16(unsigned short shortValue){
 
return ((shortValue & 0x00FF ) <<8) | ((shortValue & 0xFF00)>>8);
}

 
int 型(原理都一样!):
 
int swapInt32(int intValue){
int temp = 0;
temp = ((intValue & 0x000000FF) <<24) +
             ((intValue & 0x0000FF00) <<8) +
             ((intValue & 0x00FF000) >>8) +
             ((intValue & 0xFF000000) >>24);
 
return temp;
}

 

本博主自己改造如下:

 

void swap16(uint16_t *shortValue){
 
*shortValue =  ((*shortValue & 0x00FF ) <<8) | ((*shortValue & 0xFF00)>>8);
}
void swap32(uint32_t *intValue){
 
*intValue =  ((*intValue & 0x000000FF) <<24) +
             ((*intValue & 0x0000FF00) <<8) +
             ((*intValue & 0x00FF0000) >>8) +
             ((*intValue & 0xFF000000) >>24);
}

int swap(uint16_t type, uint8_t *data, uint16_t length, uint16_t offset)
{

	if (type == 16) {	
    	if ((offset+2) > (length)) {
				return -1;
	    }		
		swap16((uint16_t *)&data[offset]);
	}
	else if  (type == 32) {
    	if ((offset+4) > (length)) {
				return -1;
	    }			
		swap32((uint32_t *)&data[offset]);
	}
	else {
		return -1;
	}
	return 0;	
}

测试:
uint8_t data[10] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99};


	swap(16,data,sizeof(data),1);
	swap(32,data,sizeof(data),3);
	swap(16,data,sizeof(data),5);
	swap(32,data,sizeof(data),6);
	swap(32,data,sizeof(data),7);



谁看到觉得有bug,帮忙指出。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值