
Untitled
By:
ffoxin on
May 4th, 2012 | syntax:
C++ | size: 0.86 KB | hits: 17 | expires: Never
#include <iostream>
void bin_out( unsigned number )
{
bool pos = false;
bool first = false;
for( size_t i = sizeof( number ) * 8; i > 0; --i )
{
pos = ( number & ( 1 << ( i - 1 ) ) ) ? 1 : 0;
first = first || pos;
std::cout << ( first ? ( pos ? "1" : "0" ) : " " );
}
std::cout << std::endl;
}
unsigned mask( size_t length )
{
if( length > sizeof( unsigned ) * 8 )
{
length = sizeof( unsigned ) * 8;
std::cout << "Too large length. Truncated to " << length << std::endl;
}
unsigned mask = 0;
for( size_t i = 0; i < length; ++i )
mask |= 1 << i;
return mask;
}
int main( int argc, char **argv )
{
int num;
int length;
std::cout << "Enter the number and mask length:" << std::endl;
std::cin >> num >> length;
bin_out( num );
bin_out( mask( length ) );
bin_out( num & mask( length ) );
return 0;
}