# Example of Bit Manipulation in C++

Access on the level of bit is the beauty and power of C++. Bit Manipulation is not a thing which may be used very frequently but if you are working with a very limited resources, it can be very handy. Below is an example showing converting integers into binary and binary to integers by manipulating bits.

#include <bitset>

#include <iostream>

#include <string>

#include <limits>

using namespace std;

int main()

{

// print some numbers in binary representation

cout << “267 as binary short: ”

<< bitset<numeric_limits<unsigned short>::digits>(267)

<< endl;

cout << “267 as binary long: ”

<< bitset<numeric_limits<unsigned long>::digits>(267)

<< endl;

cout << “10,000,000 with 24 bits: ”

<< bitset<24>(1e7) << endl;

// transform binary representation into integral number

cout << “\”1000101011\” as number: ”

<< bitset<100>(string(“1000101011″)).to_ulong() << endl;

}

/* output will be as follows:

267 as binary short: 0000000100001011

267 as binary long: 00000000000000000000000100001011

10,000,000 with 24 bits: 100110001001011010000000

1000101011” as number: 555

*/

Posted on March 21, 2013, in C++ and tagged Binary number, Bit. Bookmark the permalink. Leave a comment.

## Leave a comment

## Comments 0