位操作 - 如何在 C++ 中计算二进制位

bit manipulation - how to calculate binary bits in c++?

本文关键字:计算 二进制 C++ 位操作      更新时间:2023-10-16

如何在 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] = '';

    // displays bit in a specific format
    for (i = 0; i < BIT; i++)
    {
        if ((i % 8) == 0)
        cout << " ";
        cout << bit[i];
    }
}

请阅读此 http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary#dec2bin。它既有算法又有样本。快乐学习:)。

while (x != 0)
{
    std::cout << (x % 2);
    x /= 2;
}