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

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

w

Connecting to %s