int x = 5;
cout<<(char)x;
the code above outputs an int x in raw binary, but only 1 byte. what I need it to do is output the x as 4-bytes in binary, because in my code, x can be anywhere between 0 and 2^32-1, since
cout<<(int)x;
doesn't do the trick, how would I do it?
To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order. Here is an example of such conversion using the integer 12.
To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.
Binary number is a base 2 number because it is either 0 or 1. Any combination of 0 and 1 is binary number such as 1001, 101, 11111, 101010 etc. Let's see the some binary numbers for the decimal number.
Binary integers for data are 0 and 1. The binary system is a kind of number system that uses a simplified notation to reduce our modern counting to only the integers one and zero. A binary integer is one of these ones and zeros that make up a binary string, and is a whole number.
A bit late, but, as Katy shows in her blog, this might be an elegant solution:
#include <bitset>
#include <iostream>
int main(){
int x=5;
std::cout<<std::bitset<32>(x)<<std::endl;
}
taken from: https://katyscode.wordpress.com/2012/05/12/printing-numbers-in-binary-format-in-c/
You can use the std::ostream::write()
member function:
std::cout.write(reinterpret_cast<const char*>(&x), sizeof x);
Note that you would usually want to do this with a stream that has been opened in binary mode.
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