Home > Back-end >  Convert decimal to binary and let binary length always eight using C
Convert decimal to binary and let binary length always eight using C

Time:11-12

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:

This is what I get:

255 > 11111111

5 -> 101

This is what I want:

255 -> 11111111

5 -> 00000101

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related