C/C++通过位操作实现2个uint32_t合并为uint64_t

#include 
using namespace std;

int main()
{
	uint32_t a = 10;
	uint32_t b = 600;
	//先将uint32_t的a转为uint64_t,此时a前面32位都是0,然后左移32位,此时右32位为0,最后加上uint32_t类型的b,填充右32位的0
	uint64_t val = (((uint64_t)a) << 32) + b;
	cout << a << " " << b << endl;
	cout << val << endl;

	{
		//先将uint64_t的值右移32位并转为int类型,就能获取之前uint32_t类型的a值
		int a1 = (int)(val >> 32);
		//uint32_t的b值可以直接将uint64_t的值强转为int(uint32_t)即可,就可以获取原值
		int a2 = (uint32_t)val;
		cout << a1 << " " << a2 << endl;
	}

	return 0;
}
/*
输出结果:
10 600
42949673560
10 600
*/

C/C++通过位操作实现2个uint32_t合并为uint64_t_第1张图片

你可能感兴趣的:(c语言,c++,开发语言)