在C ++中转换为二进制 [英] Converting to binary in C++

查看:107
本文介绍了在C ++中转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个将数字转换成二进制的函数.由于某种原因,它无法正常工作.它给出了错误的输出.输出为二进制格式,但是对于以零结尾的二进制数字,它总是给出错误的结果(至少我注意到了.)

I made a function that converts numbers to binary. For some reason it's not working. It gives the wrong output. The output is in binary format, but it always gives the wrong result for binary numbers that end with a zero(at least that's what I noticed..)

unsigned long long to_binary(unsigned long long x)
{
    int rem;
    unsigned long long converted = 0;

    while (x > 1)
    {
        rem = x % 2;
        x /= 2;
        converted += rem;
        converted *= 10;
    }

    converted += x;

    return converted;
}

请帮助我修复它,这真令人沮丧.

Please help me fix it, this is really frustrating..

谢谢!

推荐答案

  1. 您正在反转位.
  2. 在终止循环时,不能将x的剩余部分用作指标.

考虑例如4.

第一次循环迭代后:

rem == 0
converted == 0
x == 2

第二次循环迭代后:

rem == 0
converted == 0
x == 1

然后将其设置为转换为1.

And then you set converted to 1.

尝试:

int i = sizeof(x) * 8; // i is now number of bits in x
while (i>0) {
  --i;
  converted *= 10;
  converted |= (x >> i) & 1;
  // Shift x right to get bit number i in the rightmost position, 
  // then and with 1 to remove any bits left of bit number i,
  // and finally or it into the rightmost position in converted
}

使用x作为值为129的无符号字符(8位)(二进制10000001)运行上面的代码

Running the above code with x as an unsigned char (8 bits) with value 129 (binary 10000001)

i = 8开始,无符号char * 8的大小.在第一个循环迭代中,i将为7.然后取x(129)并将其右移7位,得出值1.这是对converted进行或"运算后变为1.下一次迭代,我们将converted乘以10(现在为10),然后将x右移6位(值变为2)并将其与1(值变为0).我们将0与converted进行或运算,然后仍然为10.第3-7次迭代执行相同的操作,将converted乘以10,并从x中提取一个特定的位,然后将其与或成为converted.经过这些迭代后,converted为1000000.

Starting with i = 8, size of unsigned char * 8. In the first loop iteration i will be 7. We then take x (129) and shift it right 7 bits, that gives the value 1. This is OR'ed into converted which becomes 1. Next iteration, we start by multiplying converted with 10 (so now it's 10), we then shift x 6 bits right (value becomes 2) and ANDs it with 1 (value becomes 0). We OR 0 with converted, which is then still 10. 3rd-7th iteration do the same thing, converted is multiplied with 10 and one specific bit is extracted from x and OR'ed into converted. After these iterations, converted is 1000000.

在最后一次迭代中,第一个converted乘以10并成为10000000,我们将x右移0位,得到原始值129.我们将x与1进行和,得到值1.对converted进行或"运算,即为10000001.

In the last iteration, first converted is multiplied with 10 and becomes 10000000, we shift x right 0 bits, yielding the original value 129. We AND x with 1, this gives the value 1. 1 is then OR'ed into converted, which becomes 10000001.

这篇关于在C ++中转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆