Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert decimal to binary and let binary length always eight using C++

I need a way to convert a decimal number into a binary number in c++, but the problem is, that the length of the binary number always has to be 8bit. Is there a way to do this?

I already did a conversion like this, but the length is not always 8bits:

int DecimalToBinary(int decimal)
{
    int binary = 0;
    int count = 1;
    while (decimal != 0) {
        int res = decimal % 2;
        decimal /= 2;
        binary += res * count;
        count *= 10;
    }
    return binary;
}

Here is a little example of what I want to get as output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is what I get:

255 > 11111111

5 -> 101

This is what I want:

255 -> 11111111

5 -> 00000101

>Solution :

Note that you’re not converting decimal to binary, you’re converting to another decimal number of which the output mimics a binary number. (for value five you’re really outputting value one-hundered-and-one)

But you can use std::bitset to get the output you want :

#include <bitset>
#include <iostream>

int main()
{
    // sets of 8 bits
    std::bitset<8> twofivefive{ 255 };
    std::bitset<8> five{ 5 };

    // output : 11111111
    std::cout << twofivefive.to_string() << "\n";

    // output : 00000101
    std::cout << five.to_string() << "\n";

    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading