如何在c ++中为数字设置位为ON 例如:
对于64位平台上的数字0:位是
00000000 00000000 00000000 00000000
对于64位平台上的数字2000000000:位是
01110111 00110101 10010100 00000000
到目前为止,这是我的代码:
#include<iostream>
#include<limit.h>
const int BIT = CHAR_BIT * CHAR_BIT; // CHAR_BIT states the architecture of platform
// 8 byte(64 bit) 4 byte(32 bit)
int main()
{
char* bit = new char[BIT + 1];
int i;
for ( i = 0; i < BIT + 1; i++)
bit[i] = '0';
unsigned int x;
cout << "Enter number";
cin >> x;
if (x == /* some value */)
{
// then calculate which zero's should turn to one as per number
// or how can i do this using loops
}
bit[i] = '\0';
// displays bit in a specific format
for (i = 0; i < BIT; i++)
{
if ((i % 8) == 0)
cout << " ";
cout << bit[i];
}
}
答案 0 :(得分:1)
请阅读http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary#dec2bin。 它有算法和样本。快乐学习:)。
答案 1 :(得分:0)
while (x != 0)
{
std::cout << (x % 2);
x /= 2;
}