bijlikamasla
bijlikamasla

Reputation: 371

decimal to 8 bit binary conversion in c++

I am working on decimal to binary conversion. I can convert them, using char bin_x [10]; itoa (x,bin_x,2); but the problem is, i want answer in 8 bits. And it gives me as, for example x =5, so output will be 101, but i want 00000101. Is there any way to append zeros in the start of array? or is it possible to get answer in 8 bits straight away? I am doing this in C++

Upvotes: 5

Views: 18873

Answers (3)

ssmir
ssmir

Reputation: 1542

itoa() is not a standard function so it's not good to use it if you want to write portable code.

You can also use something like that:

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 using bitset would be better.

Upvotes: 0

David Weiser
David Weiser

Reputation: 5205

To print out 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.
}

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490398

In C++, the easiest way is probably to use a 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

Upvotes: 12

Related Questions