C++: How to see a byte's bits

If you ever go down to the dungeons to slay a draconic bug, this little function, adapted from the one written by Bruce Eckel (see Reference), may be a helpful torch.

string printBinary(const unsigned char val) {
   string binaryString="";
   for(int i = 7; i >= 0; i--){
      if( val & (1 << i) ){
         binaryString += "1";
      }else{
         binaryString += "0";
      }
   }
   return binaryString;
}

Reference:

Thinking in C++, Vol One, Chapter 3: The C in C++, section: "Shift operators"

Comments

Popular posts from this blog

VB.NET: Raise base class events from a derived class

Apache Kafka - I - High level architecture and concepts

Upgrading Lodash from 3.x to 4.x