gpt4 book ai didi

c - 反转C中整数的位

转载 作者:行者123 更新时间:2023-12-01 13:32:09 24 4
gpt4 key购买 nike

我正在尝试反转 C 程序中整数的位。即使我看过the same question by another user ,我无法理解所写的大部分代码。我注意到我的代码类似于 the answer by Eregrith但我无法确定以下代码的问题:

#include <stdio.h>
#include <stdlib.h>

unsigned int reverse_bits(unsigned int num)
{
unsigned int reverse_num = 0; /* initialize the result*/
unsigned int count = sizeof(unsigned int) * 8 - 1; /* counter to track the number of bits in the integer*/

while (num != 0)
{
unsigned int last_bit = num & 1; /* get the right-most bit*/
reverse_num = reverse_num | last_bit; /* add that bit to the right-most bit of the desired reversed bits*/
reverse_num = reverse_num << 1; /* shift the reversed bits left*/
num = num >> 1; /* shift the original bits right*/
count--;
}
reverse_num = reverse_num << count; /* If the original bits have only 0
s then shift the remaining bits left*/

return reverse_num;
}

int main()
{

reverse_bits(1);
}

如果我输入 reverse_bits(1),代码返回 -2147483648,这显然没有反转整数 1 的位。我是新手,我很难找到源这个错误。在不必更改整个代码的情况下,如何修改现有代码以返回正确的输出?

最佳答案

您如何观察到它返回负值? unsigned int 仅在您的代码中使用...我假设您尝试使用 %d 将返回值打印为 int,但这是未定义的行为。要打印未签名的,您必须使用 %u%x

但是你的反转是错误的。在添加最后一位后移动结果,这应该是相反的。您还会错过 unsigned int 中的位数(减一)。以下应该有效:

#include <stdio.h>
#include <stdlib.h>

unsigned int reverse_bits(unsigned int num) {
unsigned int reverse_num = 0; /* initialize the result*/
unsigned int count = sizeof(unsigned int) * 8; /* counter to track the number of bits in the integer*/

while (num != 0) {
unsigned int last_bit = num & 1; /* get the right-most bit*/
reverse_num <<= 1; /* add one place for the next bit */
reverse_num |= last_bit; /* add that bit to the right-most bit of the desired reversed bits*/
num >>= 1; /* remove one bit from the original */
count--;
}
reverse_num <<= count; /* If the original bits have only 0 s then shift the remaining bits left*/
return reverse_num;
}

int main() {
printf("%08x\n",reverse_bits(1));
printf("%08x\n",reverse_bits(3));
printf("%08x\n",reverse_bits(0x0F0FFFFF));
}

---- 编辑----

如评论所述可能吗? UB 在 num begin null 的情况下,我建议添加一个测试来消除该问题:

  if (count!=sizeof(reverse_num)) {
reverse_num <<= count; /* If the original bits have only 0 s then shift the remaining bits left*/
} else {
reverse_num = 0;
}
return reverse_num;

关于c - 反转C中整数的位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45428779/

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