Printing integers in binary format


I’m using ROOT as a command line calculator and I’m very happy with it. I just wonder whether there is an easy way to display integers in binary format. Something like

root [0] itoa(5) 101

Thanks, Kašpi.

root [0] for ( int i = 31; i >= 0; i-- ) cout << (5 >> i & 1); cout << endl;

Or, if you just want to be able to read the binary yourself, hex is considerably easier to read.

root [1] cout << hex << 65535 << endl;

The ‘hex’ keyword is located in the header, so if you want to use it in a compiled program, you need to #include followed by using std::hex; or using namespace std; … s/hex.html

The important thing to realise is that each hexadecimal digit means 4 bits. So FF = 1111 1111, F1 = 1111 0001, etc.


  • Peter


also, CINT offers a custom “%b” format specifier: printf("%b\n",5); will display 101.

Cheers, Axel.

Thanks very much. This is the sort of thing I was looking for.

Cheers, Kaspi.