Using the STL Library in C++, part 3

Today – bit operations. Logical & Arithmetic, using the STL, something like  a simple calculator:


#include <iostream>
#include <bitset>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
 {
 for(;;)
 {
 bitset <4> myBit; // here you have to define the size of bitspace and create it
 cout << "Insert first number(4 bits): " << endl;
 cin >> myBit;

cout << endl;
 bitset <4> myBit2;
 cout << "Insert second number(4 bits): " << endl;
 cin >> myBit2;
 cout << endl;

cout << "Logical operations: " << endl;
 cout << "AND: " << (myBit & myBit2) << endl << "OR : " << (myBit | myBit2) << endl << endl; //logical operations & AND and | OR

cout << "Then arithmetic operations: " << endl;

bitset <5> myAddedBits = (myBit.to_ulong() + myBit2.to_ulong()); //here you have to create a new bitspace and define it with addition of to bitspaces
 cout << "Sum in BIN: " << myAddedBits << endl; //result in binary system
 cout << "Sum in DEC: " << (myBit.to_ulong() + myBit2.to_ulong()) << endl << endl; //result in decimal system

bitset <8> myMultipliedBits = (myBit.to_ulong() * myBit2.to_ulong());
 cout << "Multiplication in BIN: " << myMultipliedBits << endl;
 cout << "Multiplication in DEC: " << (myBit.to_ulong() * myBit2.to_ulong()) << endl;

cout << "Insert Q to quit or C to continue!" << endl;

char x;
 cin >> x;

if(x == 'Q' || x == 'q')
 {
 cout << "The end! \n";
 break;
 }
 else
 {
 continue;
 }
 }

return 0;
 }

After compilation, it looks like this:

MJ

One thought on “Using the STL Library in C++, part 3

Zostaw komentarz

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s