尝试了解下面代码块的结果可能是什么。 这是否意味着我们在数组的第一个元素中设置位?
U16_SET_BIT(候选[1], 0);
这是否意味着我们采用 unsigned int 类型的常量 1 并进行 n 位位移,在本例中为 0。
#define U16_CREATE_MASK(n) (1U << (n))
这是我更困惑的下一个或部分。上面的运算将为我们提供 32 位,然后我们尝试与 16 位进行“或”运算?
#define U16_SET_BIT(u, n) (u |= U16_CREATE_MASK(n))
#define U16_CREATE_MASK(n) (1U << (n))
#define U16 unsigned short
int main(void) {
....
U16 candidates[13];
U16_SET_BIT(candidates[1], 0);
....
}
最佳答案
U16_SET_BIT(candidates[1], 0);
Does this mean we setting bits in first element of array ?
是的,它将第二个(从 0 开始计数)元素的 LSB 设置为 1。
Does this mean we are taking constant 1 of type unsigned int and doing bitshift by n bits, in this case it would be 0.
是的。这样做是为了获得正确的掩码值,以便稍后进行“或”运算。
Operation above will give us 32bits and then we trying to do OR with 16bits ?
在移位之前,两个操作数都会被提升。因此,您将拥有两个 int 大小的操作数。转换后,如果您将其分配给更窄的类型,则转换将是实现定义的。通常,您会将模 2n 值作为结果,其中 n 是目标类型中的位数。这本质上意味着高阶位被丢弃。
关于c - 是否可以在 unsigned int 和 unsigned Short 之间进行按位或赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32514084/