C++: Cómo ver los bits de un byte

Si algún día tenemos necesidad de bajar a las mazmorras para matar un bug dracónico, esta funcioncita, adaptada de la que escribió Bruce Eckel para "Thinking in C++" (ver referencia), puede servir de antorcha:

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;
}

Referencia:

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

Comments

Popular posts from this blog

Upgrading Lodash from 3.x to 4.x

C++/CLI: Trigger events from C++ native code and handle them in Managed code, Part I

Traduciendo un custom control de Windows Forms de VB.NET a C#