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

*/

Advertisements

About Khuram Ali

Programming... Programming and Programming...!!!

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: