欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C/C++ 16bit转8bit

程序员文章站 2022-07-01 21:00:22
...
#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;
}