十进制到二进制转换

Decimal to Binary Conversion

本文关键字:转换 二进制 十进制      更新时间:2023-10-16

我正在编写一个函数,用于在十进制和二进制基数系统之间进行转换,下面是我的原始代码:

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)

,这两种形式有什么区别?

当您输入while (number)时,number(即int)被转换为bool类型。如果为零,则为false,如果为非零,则为true

当你说while (number == true)时,true被转换为int(成为1),它就像你说while (number == 1)一样。

下面是我的代码....

    #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] = '';
    for (i = bitsCount - 1; i >= 0; --i, value >>= 1)
      {
             output[i] = (value & 1) + '0';
      }
}

  int main()
   {
    char s[50];
    tobinstr(65536,32, s);
    printf("%sn", s);
    return 0;
   }