showBits.cpp

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3100/spring2026/notes/binary/code/showBits.cpp
 
#include <iostream>
#include <format>
#include <type_traits>
#include <limits>

using namespace std;

template <typename T> 
string MyIntBits(T number) {

   T bit{1};
   int shifts{0};
   bool firstDigit{false};
   string s;

   bool keepGoing{true};

   while (keepGoing){
      
      if (number & bit) {
         s = '1' + s;
         firstDigit = true;
      } else {
         if (firstDigit) {
             s = '0' + s;
         }
      }

      ++shifts;
      bit = bit << 1;

      if (number > 0 and bit > number) {
         keepGoing = false;
      }  else if (shifts ==  sizeof(T) * 8) {
         keepGoing = false;
      }
   }

   if (not firstDigit) {
      s = '0';
   }

   return s;
}

void SpacePrint(string s) {
   int count {0};
   for(int i = s.size()- 1; i >= 0; --i) {
       count++;
       if (count == 4) {
           s.insert(i, " ");
           count = 0;
       }
   }
   cout << "in binary the number is " << s << endl;
}

template <typename T>
void ShowBits(T number) {  
   cout << " Input :  " << number << endl;

   if (sizeof(T) == 1) {
       int asInt {static_cast<int>(number)};
       cout << "in decimal the number is " << asInt << endl;
       cout << "in hex the number is " << std::hex << asInt << endl;
       cout << "in octal the number is " << std::oct << asInt << endl;
   } else {
      cout << "in decimal the number is " << number << endl;
      cout << "in hex the number is " << std::hex << number << endl;
      cout << "in octal the number is " << std::oct << number << endl;
   }
   cout << std::dec;
   if constexpr (std::is_integral_v<T>) {
       SpacePrint(format("{:b}",number));
       SpacePrint(MyIntBits(number));
   }

}

int main() {
   int number {1024+512+256+32 + 8 + 4 +1};

   cout << endl;

   ShowBits(number);

   cout << endl;

   ShowBits('a');

   cout << endl;
   ShowBits(-number);
   cout << endl;

   unsigned short  smallNum{numeric_limits<unsigned short>::max()};
   ShowBits(smallNum);
   cout << endl;

   long int  bigNum{numeric_limits<long int>::max()};
   ShowBits(bigNum);
   cout << endl;

   return 0;
}