【发布时间】:2021-01-26 12:22:17
【问题描述】:
我想重置 int32_t 的第 31 位(最后一位,0 到 31 范围),只有这种情况似乎失败了。 即,当“i”为 31 时,输出失败,它返回 -1。错误是什么?如何解决?
#include <stdio.h>
#include <stdlib.h>
void Release(int ResetBit, int32_t *Val)
{
int32_t testBit = 1; /* XoR Bit */
if (ResetBit >= 0 && ResetBit < 32)
{
testBit = (testBit << ResetBit);
*Val ^= testBit;
}
else
{
perror("Max range is 0-31 only, failed! ");
//exit(1);
}
}
int main(int argc, char const *argv[])
{
int count = 0;
for (int i = 0; i < 32; i++)
{
int32_t MaxValue = 2147483647;
Release(i, &MaxValue);
printf("MaxValue = %d NodeID = % d\n", MaxValue, i);
count++;
}
printf("%d", count);
return 0;
}
情况 i = 31 的输出是:
MaxValue = -1 节点 ID = 31
【问题讨论】:
-
好吧,不要为此使用有符号整数(移位有符号整数可能会导致未定义的行为)。使用无符号,即
uint32_t。除此之外,您还不清楚Release是什么意思——它是“设置为零”还是“切换位”? -
我想“设置为零”一个特定的位(在 0-31 范围内)。要将特定位设置为零,我将“i”作为位位置传递。例如:将第 5 位设置为零,i = 4。
-
@4386427 我尝试使用 u_int32_t,它给出了同样的错误
-
结果没有任何问题,它是您的所有位设置的签名值。如果你想看到未签名的使用
unsigned和打印%u。
标签: c memory memory-management bitmap out-of-memory