Reputation: 1
The assignment I attempted to do is past its due date, so you are not doing my homework.
For the sake of learning, I would like to know how to do a few things.
I was able to make a program, with a mask using bitwise operators print out 1-32 in binary.
The problem with the mask I used is that it would also print out 32 leading zeros, followed by the binary number (ex. 0000000000000000000000000000000001 for the number 1)
This is what I had
# include <iostream>
#include <string>
using namespace std;
string naiveBitToChar( int num )
{
string st;
unsigned mask = 0x80000000;
if( num == 0 )
{
return "0";
}
while( ( num & mask ) )
mask >>= 1;
do
{
if ( num & mask )
{
st = st + "1";
}
else
{
st = st + "0";
}
mask >>= 1;
}
while( mask );
return st;
}
int main ( int argc, char* argv[] ) {
argc; argv;
for( int i = 0; i < 32; i++ )
cout << naiveBitToChar(i) << "\n";
system ("pause");
}
I needed to:
I am new to C++, my teacher would not even look at my code, please someone explain, and try to keep it basic. Thank you!
Upvotes: 0
Views: 1021
Reputation: 44238
If you scan from right to left, then it will be easier, as you do not need to remove leading zeros, but just to stop when number is 0:
std::string binary( unsigned n )
{
std::string bits;
for( unsigned mask = 1; true; mask <<=1 ) {
bits.insert( bits.begin(), n & mask ? '1' : '0' );
n &= ~mask;
if( !n ) break;
}
return bits;
}
Or even simpler:
std::string binary( unsigned n )
{
std::string bits;
do {
bits.insert( bits.begin(), n & 1 ? '1' : '0' );
n >>= 1;
} while( n );
return bits;
}
To change minimum witdth you would need to modify loop condition slightly, to add unserscore can be as simple as:
if( bits.length() % 4 ) bits.insert( bits.begin(), '_' );
inside loop
Upvotes: 0
Reputation: 57678
Here's an idea, use a flag to indicate a leading zero digit. Change the flag if the bit is a one. Print the digit only if it is not a leading zero.
bool is_leading_zero = true;
while (/*... */)
{
// Convert bit to character in st
if (st == '1')
{
is_leading_zero = false;
}
if (!is_leading_zero)
{
cout << st;
}
}
Upvotes: 1