Tuesday, September 18, 2012

Outputting Data in Binary.


C++ doesn't have an easy way to print out an integer in binary, so I ended up rolling my own method today.  I vaguely recall doing this before but I'm fairly certain I targeted a particular data type.  This time around I figured I might as well just use templates so I can handle any data type.

All this just so I could let my brain be lazy and not have to mentally translate hex to binary.  Which of course I was doing to make sure I was feeding proper input to a rather meaningless probability experiment.  I'm not so sure I took the easy way out at this point.

Along the way, the precedence of the bitwise operator & caused me some grief.  It's lower than the == operator so my expressions were unexpectedly evaluating to true.  I learned a bit of history as to why things seem brain damaged.

Anyhow, here's some code:

template <typename T>
void toBinary(T data) {
  unsigned char *currentByte = (unsigned char *) &data;
  unsigned char mask = 0x01;
  std::string byteString;
  std::string output = "";

  currentByte = currentByte + sizeof(T) - 1;

  //loop through each byte of data
  for (int i = sizeof(T); i > 0; i--) {

    //convert each byte to a binary string
    byteString = "";
    for (int j = 0; j < 8; j++) {
      if (*currentByte & mask) {
        byteString = "1" + byteString;
      } else {
        byteString = "0" + byteString;
      }
      *currentByte = *currentByte >> 1;
    }

    output = output + byteString;
    currentByte--;
  }
  std::cout << output << std::endl;
}

No comments:

Post a Comment