Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

decimal to 8 bit binary conversion in c++

Tags:

c++

binary

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++

like image 998
bijlikamasla Avatar asked Feb 07 '11 16:02

bijlikamasla


People also ask

How do you convert binary to 8?

8 in binary is 1000. Unlike the decimal number system where we use the digits 0 to 9 to represent a number, in a binary system, we use only 2 digits that are 0 and 1 (bits).

How do you convert a decimal number to binary?

The simplest way to convert a decimal number to a binary number is by dividing the given number repeatedly by 2 until we get 0 as the quotient. Then, we write the remainders in the reverse order to get the binary value of the given decimal number.


1 Answers

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

like image 66
Jerry Coffin Avatar answered Sep 30 '22 14:09

Jerry Coffin