C/C++ 16bit转8bit

#include <iostream>
/*
16bit转8bit
@param 1,数组首地址
@param 2,数组大小
@return ,
	1.失败,返回NULL
	2.成功,转换完成的8bit数组
	3.需要手动释放内存
*/
unsigned char *_16bit_convert_8bit(unsigned short *_16bit,unsigned int size)
{
	size *= 2;
	unsigned char *_8bit = new unsigned char[size];
	memset(_8bit, 0x0, size);
	if (!_8bit) {
		std::cout << "failed to new memory" << std::endl;
		return NULL;
	}

	/*判断是大端还是小端*/
	int big_endian = 1;
	unsigned short _s = 0x1122;
	unsigned char *_c = (unsigned char *)&_s;
	if (*_c == 0x22)
		big_endian = 0;

	for (unsigned int i = 0,j = 0; i < size; i++,i++,j++)
	{
		if (big_endian)
		{
			_8bit[i] = _16bit[j] >> 8;
			_8bit[i + 1] = _16bit[j] & 0xff;
		}
		else
		{
			_8bit[i] = _16bit[j] & 0xff;
			_8bit[i + 1] = _16bit[j] >> 8;
		}
	}
	return _8bit;
}

int main()
{
	unsigned short a[] = {0x1122,0x2211,0x3344,0x4433};
	unsigned char *result = _16bit_convert_8bit(a,sizeof(a) / sizeof(unsigned short));
	std::cout << (int *)result << std::endl;
        delete [] result;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值