//*********************************************************************************************** //File: Binary.h //Header file del Binary ADT //By Hector Serrano //*********************************************************************************************** #include "Stacks.h" using namespace std; #ifndef BINARY_H #define BINARY_H const int ARRAY_SIZE = 16; //************************************Class Definition******************************************* class Binary { private: int binArray[ARRAY_SIZE]; void addBit(int aBit, int anotherBit, int& carryBit, int& sum); public: Binary(int number); //Constructor Binary operator + (Binary anotherBinary); //Trasformador void getBinaryValue(int bitArray[])const; //Observador int getDecimalValue() const; //Observador }; //*********************************Member Function Definition************************************ //Convierte un numero decimal a un numero binario Binary::Binary(int number) { int quotient, remainder, numOfBits = 0, index, num; Stack binStack; quotient = number; while (quotient != 0) { remainder = quotient % 2; quotient = quotient / 2; binStack.push(remainder); numOfBits++; } for (index = 0; index < ARRAY_SIZE - numOfBits - 1; index++) binArray[index] = 0; binArray[index] = 0; while (!binStack.isEmpty()) { binStack.pop(num); index++; binArray[index] = num; } } //Devuelve un valor decimal de un numero binario int Binary::getDecimalValue() const { int index = 0, number; number = binArray[index]; while (index < ARRAY_SIZE - 1) { number = number * 2; index++; number = number + binArray[index]; } return number; } //Devuelve el valor binario de un numero decimal; void Binary::getBinaryValue(int bitArray[]) const { for (int i = 0; i < ARRAY_SIZE; i++) bitArray[i] = binArray[i]; } //Para sumar dos objectos Binarios Binary Binary::operator + (Binary anotherBinary) { int aBit, anotherBit, carryBit = 0, sum; Binary resultBin(0); for (int i = ARRAY_SIZE - 1; i >= 0; i--) { aBit = binArray[i]; anotherBit = anotherBinary.binArray[i]; addBit(aBit, anotherBit, carryBit, sum); resultBin.binArray[i] = sum; } return resultBin; } //Para sumar los Bits void Binary::addBit(int aBit, int anotherBit, int& carryBit, int& sum) { int answer; answer = aBit + anotherBit + carryBit; switch (answer) { case 0: carryBit = 0; sum = 0; break; case 1: carryBit = 0; sum = 1; break; case 2: carryBit = 1; sum = 0; break; case 3: carryBit = 1; sum = 1; break; } } #endif