C++中按位写入读取数值

Posted 星火撩猿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++中按位写入读取数值相关的知识,希望对你有一定的参考价值。

向 quint8类型数据中连续位写入数值

void Utils::insertValueToQuint8CtrlWord(quint8* unsigned8CtrlWord, int high_position, int low_postion, quint16 setValue)

	int len = high_position - low_postion;
	switch (len)
	
	case 0:
		setValue = setValue & 0x00000001;
		break;
	case 1:
		setValue = setValue & 0x00000003;
		break;
	case 2:
		setValue = setValue & 0x00000007;
		break;
	case 3:
		setValue = setValue & 0x0000000f;
		break;
	case 4:
		setValue = setValue & 0x0000001f;
		break;
	case 5:
		setValue = setValue & 0x0000003f;
		break;
	case 6:
		setValue = setValue & 0x0000007f;
		break;
	case 7:
		setValue = setValue & 0x000000ff;
		break;
	default:
		break;
	

	bitset<32> binaryControlWord(*unsigned8CtrlWord);
	for (int i = low_postion; i <= high_position; i++)
	
		binaryControlWord.reset(i);
	

	bitset<32> binaryValue(setValue);
	binaryValue <<= low_postion;
	binaryControlWord |= binaryValue;
	*unsigned8CtrlWord = (quint32)binaryControlWord.to_ulong();

从 quint8类型数据中连续位读取数值

int Utils::getValueFromQuint8CtrlWord(quint8* unsigned8CtrlWord, int high_position, int low_postion)

	int ret = 0;

	bitset<16> binaryCtrlWord(*unsigned8CtrlWord);

	for (int i = 0; i < low_postion; i++) binaryCtrlWord.reset(i);
	for (int i = high_position + 1; i <= 7; i++) binaryCtrlWord.reset(i);

	binaryCtrlWord >>= low_postion;

	ret = (quint8)binaryCtrlWord.to_ulong();

	return ret;

说明:quint16,quint32,quint64类型数据类似方法实现。

以上是关于C++中按位写入读取数值的主要内容,如果未能解决你的问题,请参考以下文章

é 如何在 C++ 中按位移动到 E?

C语言有效位

在 Python 中按位与 0xFFFFFFFF

在 C++ 中按字符读取输入文件时的换行符

为啥在 OpenCV Python 中按位发送错误?

C中按位运算的模运算