Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Binary!

Status
Not open for further replies.

grande

Programmer
Feb 14, 2005
657
0
0
CA
Is there an easy way to convert a number to binary? Perhaps something similar to the %x for Hex?

-------------------------
Just call me Captain Awesome.
 
You could use a bitset:
Code:
#include <iostream>
#include <bitset>

int main()
{
    //                     1   1   0   0   1   1   0   0   1   1
    unsigned long value = 512+256+ 0 + 0 + 32+ 16+ 0 + 0 + 2 + 1;
    std::bitset<12> bits(value);

    std::cout << "Decimal: " << value << std::endl;
    std::cout << "Binary : " << bits << std::endl;
}
Notice that you have to specify the number of bits, and all bits are output in this example, including leading 0's.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top