Display a byte in binary - C++ Data Type

C++ examples for Data Type:byte

Description

Display a byte in binary

Demo Code

#include <iostream>
#include <iostream>
using namespace std;
void printBinary(const unsigned char val) {
   for(int i = 7; i >= 0; i--)
      if(val & (1 << i))
   std::cout << "1";
else/*from  ww w.  ja va 2s. c om*/
   std::cout << "0";
}
#define PR(STR, EXPR) cout << STR; printBinary(EXPR); cout << endl;
int main() {
   unsigned int getval = 123;
   unsigned char a, b;
   a = getval;
   PR("a in binary: ", a);
   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;
   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);
}

Result


Related Tutorials