naive print bits function
I'm getting an infinite loop. I want to print from MSB to LSB. I'm not sure why its stuck...
Code:
#include <climits>
#include <iostream>
using namespace std;
template<typename t>
//Q: how do I print it from MSB to LSB
void print_bits(const t& type)
{
unsigned int mask;
size_t num_bits = sizeof(t) * CHAR_BIT;
size_t width = 0;
for ( size_t i = (num_bits - 1); i >= 0; --i )
{
mask = type & ( 1 << i);//turn off all bits except cur bit
if ( !mask )//=> if 0(base-10) it means cur bit is 0 (when cur bit is AND 1)where we turn off all bits, then output '0'
cout << mask;
else
cout << 1;//b/c if it's non-zero in base-2, then output binary 1
if ( width % 4 == 3 )
cout << " ";//to separate into 4bit chunks for readability
++width;
}
cout << endl;
}
int main()
{
unsigned int garage = 90;
cout << "Status of each garage..." << endl;
print_bits(garage);
return 0;
}
It outputs it correctly as: 0000 0000 0000 0000 0000 0000 0101 1010 (for base-10 of 90), but then repeats, why?