gpt4 book ai didi

logic - 将两个整数作为一个整数传递

转载 作者:行者123 更新时间:2023-12-04 00:40:28 26 4
gpt4 key购买 nike

我有两个整数,我需要通过一个整数然后取回两个整数的值。

我正在考虑使用逻辑运算符(AND、OR、XOR 等)。

最佳答案

使用 C 编程语言,假设两个整数小于 65535,可以按如下方式完成。

void take2IntegersAsOne(int x)
{
// int1 is stored in the bottom half of x, so take just that part.
int int1 = x & 0xFFFF;

// int2 is stored in the top half of x, so slide that part of the number
// into the bottom half, and take just that part.
int int2 = (x >> 16) & 0xFFFF

// use int1 and int2 here. They must both be less than 0xFFFF or 65535 in decimal

}


void pass2()
{
int int1 = 345;
int int2 = 2342;
take2Integers( int1 | (int2 << 16) );
}

这依赖于这样一个事实,即在 C 中整数存储在 4 个字节中。因此,该示例使用前两个字节存储其中一个整数,然后使用接下来的两个字节存储第二个。尽管每个整数都必须具有足够小的值,以便它们每个只能容纳 2 个字节,但这确实强加了限制。

移位运算符 << 和 >> 用于上下滑动整数的位。移位 16,将位移动两个字节(因为每字节有 8 位)。

使用 0xFFFF 表示数字的低两个字节中的所有位都是 1 的位模式因此,ANDing(使用 & 运算符)会导致所有不在这两个低字节中的位被关闭(回到零)。这可用于从您当前提取的整数中删除“其他整数”的任何部分。

关于logic - 将两个整数作为一个整数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4738480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com