Home > Software design >  how to add ZERO on beginning of binary number
how to add ZERO on beginning of binary number

Time:10-25

void to_binary(int x)
{

    while (x)
    {
        a4 = x % 2;
        x /= 2;
        new_b  = a4 * pow(10, g);//g=0
        g  ;
    }
}

I wrote the function of converting a number to a binary number system, but there is one but if the number has leading zero, for example, 0011, then I see only 11 in the console. Can I fix this problem? I thought through the vector and bitset but they don`t work for me also.

CodePudding user response:

You did not elaborate what was wrong with std::bitset. For me it seem to do what you want:

#include <iostream>
#include <bitset>

int main() {
    unsigned long long x = 3;

    // 8 digits
    std::cout << "x = " << std::bitset<8>(x) << std::endl;
    // 4 digits
    std::cout << "x = " << std::bitset<4>(x) << std::endl;
}

Output:

x = 00000011
x = 0011
  •  Tags:  
  • c
  • Related