Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to output an int in binary?

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?

like image 427
user299648 Avatar asked Jul 17 '10 01:07

user299648


People also ask

How do you convert int to binary?

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.

How do you print numbers in binary?

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.

How do you declare a number in binary?

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.

What is an integer in binary?

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.


2 Answers

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/

like image 55
Johann Horvat Avatar answered Sep 27 '22 21:09

Johann Horvat


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.

like image 27
James McNellis Avatar answered Sep 27 '22 22:09

James McNellis