-2

I want to output an int in 32-bit binary format. Is looping and shifting my only option?

Varaquilex
  • 3,447
  • 7
  • 40
  • 60
  • 32-bit binary format. What I meant is in the answer output. Is it not clear? Shall I edit my question? – Varaquilex Apr 30 '14 at 09:11
  • Duplicate http://stackoverflow.com/questions/7349689/c-how-to-print-using-cout-the-way-a-number-is-stored-in-memory – Moberg Apr 30 '14 at 09:14
  • @Varaquilex Well, it wasn't clear to me that you meant a text format. I guess I'm to used to hearing people use the word binary to mean not text. – James Kanze Apr 30 '14 at 09:43

1 Answers1

6

Looping is a way. You can also use bitset library.

#include <iostream>
#include <bitset>

int main(int argc, char** argv) {

    int i = -5, j = 5;
    unsigned k = 4000000000; // 4 billion
    std::cout << std::bitset<32>(i) << "\t" << std::bitset<32>(j) << std::endl;
    std::cout << std::bitset<32>(k) << std::endl;

    return 0;
}

And the output will be:

11111111111111111111111111111011       00000000000000000000000000000101
11101110011010110010100000000000
Varaquilex
  • 3,447
  • 7
  • 40
  • 60