十进制到二进制转换

时间:2011-04-24 07:54:50

标签: c++ while-loop evaluation conditional-statements boolean-expression

我正在为Decimal和Binary基数系统之间的转换编写一个函数,这是我的原始代码:

void binary(int number)
{
    vector<int> binary;

    while (number == true)
    {
        binary.insert(binary.begin(), (number % 2) ? 1 : 0);
        number /= 2;
    }

    for (int access = 0; access < binary.size(); access++)
        cout << binary[access];
}

直到我这样做才行不通:

while(number)

有什么问题
while(number == true)

这两种形式有什么区别? 提前谢谢。

2 个答案:

答案 0 :(得分:8)

当您说while (number)时,number int将被转换为bool类型。如果它为零则变为false,如果它为非零,则变为true

当您说while (number == true)时,true会转换为int(成为1),就像您说while (number == 1)一样}。

答案 1 :(得分:0)

这是我的代码......

    #include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<unistd.h>
#include<assert.h>
#include<stdbool.h>
#define max 10000
#define RLC(num,pos) ((num << pos)|(num >> (32 - pos)))
#define RRC(num,pos) ((num >> pos)|(num << (32 - pos)))

void tobinstr(int value, int bitsCount, char* output)
{
    int i;
    output[bitsCount] = '\0';
    for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
      {
             output[i] = (value & 1) + '0';
      }
}


  int main()
   {
    char s[50];
    tobinstr(65536,32, s);
    printf("%s\n", s);
    return 0;
   }
相关问题