2011-04-24 79 views
1

我写了十进制和二进制基数系统之间的转换函数,这里是我的原代码:十进制转换为二进制的转换

while(number) 

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 == true) 

,什么是两种形式之间的差别? 在此先感谢。

回答

8

当你说while (number)number,这是一个int,转换为类型bool。如果它为零,则它变成false,如果它不为零,则变成true

当你说while (number == true),该true转换为int(成为1),它是一样的,如果你说的while (number == 1)

+0

感谢您的澄清,我还在学习和推广型有时逃避我。 – 2011-04-24 08:17:53

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; 
    }