Decimal to 8-bit binary conversion in C ++

I am working on decimal binary conversion. I can convert them using char bin_x [10]; itoa (x, bin_x, 2); but the problem is that I want to answer in 8 bits. And this gives me, for example, x = 5, so the output will be 101, but I want 00000101. Is there a way to add zeros to the beginning of the array? Or can I get an 8-bit response right away? I do it in C ++

+3
source share
3 answers

In C ++, the easiest way to use is std::bitset:

#include <iostream>
#include <bitset>

int main() { 
    int x = 5;

    std::bitset<8> bin_x(x);
    std::cout << bin_x;

    return 0;
}

Result:

00000101

+10
source

To print the bits of a single digit, you need to do the following:

//get the digit (in this case, the least significant digit)
short digit = number % 10; //shorts are 8 bits

//print out each bit of the digit
for(int i = 0; i < 8; i++){
    if(0x80 & digit) //if the high bit is on, print 1
        cout << 1;
    else
        cout << 0; //otherwise print 0
    digit = digit << 1; //shift the bits left by one to get the next highest bit.
}
0
source

itoa() , , .

- :

std::string printBinary(int num, int bits) {
    std::vector<char> digits(bits);
    for (int i = 0; i < bits; ++i) {
        digits.push_back(num % 2 + '0');
        num >>= 1;
    }
    return std::string(digits.rbegin(), digits.rend());
}

std:: cout << printBinary(x, 8) << std::endl;

However, I must agree that use bitsetwould be better.

0
source

Source: https://habr.com/ru/post/1790497/


All Articles