[英]Decimal to Binary Conversion
我正在编写一个用于在十进制和二进制基数系统之间进行转换的函数,这是我的原始代码:
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)
,将int
number
转换为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] = '\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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.