ch3-Bitwise operations, print byte in binary

Chapter_3     Exercise_3-11 Exercise_3-13     Exercise_3-12







CONTENTS:     PrintBinary.hpp     PrintBinary.cpp     Bitwise.cpp




PrintBinary.hpp     TCP1, p. 173         download


// Display a byte in binary
void printBinary(const unsigned char val);





PrintBinary.cpp     TCP1, p. 173         download


// We do not have to include PrintBinary.hpp in this file
#include <iostream>
// Display a byte in binary
void printBinary(const unsigned char val)
{
for(int i = 7; i >= 0; i--)
{ // print bits from first (most significant) to last (least significant)
if(val & (1 << i)) // set (1) bit
{std::cout << "1";} // note the fully qualified cout, std::cout
else {std::cout << "0";} // 0 bit
}
}
/*
g++ -c PrintBinary.cpp // create object file
*/











Bitwise.cpp     TCP1, p. 174         download


// Demonstration of bit manipulation
#include "PrintBinary.hpp" // for printBinary()
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

// A macro to save typing:
#define PR(STR, EXPR) \
cout << STR; printBinary(EXPR); cout << endl;

int main()
{
unsigned int getval;
unsigned char a, b;

cout << "Enter a number between 0 and 255: ";
cin >> getval; a = getval;
PR("a in binary: ", a) // semicolon not required here

cout << "Enter a number between 0 and 255: ";
cin >> getval; b = getval;
PR("b in binary: ", b)

PR("a | b = ", a | b)
PR("a & b = ", a & b)
PR("a ^ b = ", a ^ b)
PR("~a = ", ~a)
PR("~b = ", ~b)

// An interesting bit pattern:
unsigned char c = 0x5A; // 90
PR("c in binary: ", c)
a |= c;
PR("a |= c; a = ", a)
b &= c;
PR("b &= c; b = ", b)
b ^= a;
PR("b ^= a; b = ", b)
}
/*
g++ -c PrintBinary.cpp Bitwise.cpp // create object files
g++ -c *.cpp
g++ PrintBinary.o Bitwise.o -o Bitwise // link object files, create executable
g++ *.o -o Bitwise
rm *.o // clean (delete object files)
./Bitwise
Enter a number between 0 and 255: 0
a in binary: 00000000
Enter a number between 0 and 255: 255
b in binary: 11111111
a | b = 11111111
a & b = 00000000
a ^ b = 11111111
~a = 11111111
~b = 00000000
c in binary: 01011010
a |= c; a = 01011010
b &= c; b = 01011010
b ^= a; b = 00000000

./Bitwise
Enter a number between 0 and 255: 26
a in binary: 00011010
Enter a number between 0 and 255: 105
b in binary: 01101001
a | b = 01111011
a & b = 00001000
a ^ b = 01110011
~a = 11100101
~b = 10010110
c in binary: 01011010
a |= c; a = 01011010
b &= c; b = 01001000
b ^= a; b = 00010010
*/





Note:  See also ch2-bitstrings on the blog Kernighan_and_Ritchie, Chapter_2, Sec. 2.9.









Chapter_3     Exercise_3-11 BACK_TO_TOP Exercise_3-13     Exercise_3-12



Comments

Popular posts from this blog

Contents