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++
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With