I was writing a function for conversion between Decimal and Binary base number systems and here's my original code:
void binary(int number)
{
vector<int> binary;
while (number == true)
{
binary.insert(binary.begin(), (number % 2) ? 1 : 0);
numbe开发者_StackOverflow中文版r /= 2;
}
for (int access = 0; access < binary.size(); access++)
cout << binary[access];
}
It didn't work however until I did this:
while(number)
what's wrong with
while(number == true)
and what's the difference between the two forms? Thanks in advance.
When you say while (number)
, number
, which is an int
, is converted to type bool
. If it is zero it becomes false
and if it is nonzero it becomes true
.
When you say while (number == true)
, the true
is converted to an int
(to become 1
) and it is the same as if you had said while (number == 1)
.
Here is my code....
#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;
}
精彩评论