while (x != 0)
{
std::cout << (x % 2);
x /= 2;
}
how to calculate binary bits in c++? [closed]
-
28-06-2023 - |
سؤال
how to set bits to ON for a number in c++ for example:
for number 0 on 64 bit platform : bits are
00000000 00000000 00000000 00000000
for number 2000000000 on 64 bit platform : bits are
01110111 00110101 10010100 00000000
here is my code so far:
#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];
}
}
المحلول 2
نصائح أخرى
Please read this http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary#dec2bin. It has both the algorithm and sample. Happy learning :).
لا تنتمي إلى StackOverflow