How can I convert a integer to its bit representation. I want to take an integer and return a vector that has contains 1's and 0's of the integer's bit representation.
I'm having a heck of a time trying to do this myself so I thought I would ask to see if there was a built in library function that could help.
To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.
Use bin() Function to Convert Int to Binary in Python In Python, you can use a built-in function, bin() to convert an integer to binary. The bin() function takes an integer as its parameter and returns its equivalent binary string prefixed with 0b .
Java's Integer class has a method named toBinaryString to convert an integer into its binary equivalent string.
toBinaryString. Returns a string representation of the integer argument as an unsigned integer in base 2. The unsigned integer value is the argument plus 232 if the argument is negative; otherwise it is equal to the argument.
Doesn't work with negatives.
vector<int> convert(int x) {
vector<int> ret;
while(x) {
if (x&1)
ret.push_back(1);
else
ret.push_back(0);
x>>=1;
}
reverse(ret.begin(),ret.end());
return ret;
}
It's not too hard to solve with a one-liner, but there is actually a standard-library solution.
#include <bitset>
#include <algorithm>
std::vector< int > get_bits( unsigned long x ) {
std::string chars( std::bitset< sizeof(long) * CHAR_BIT >( x )
.to_string< char, std::char_traits<char>, std::allocator<char> >() );
std::transform( chars.begin(), chars.end(),
std::bind2nd( std::minus<char>(), '0' ) );
return std::vector< int >( chars.begin(), chars.end() );
}
C++0x even makes it easier!
#include <bitset>
std::vector< int > get_bits( unsigned long x ) {
std::string chars( std::bitset< sizeof(long) * CHAR_BIT >( x )
.to_string( char(0), char(1) ) );
return std::vector< int >( chars.begin(), chars.end() );
}
This is one of the more bizarre corners of the library. Perhaps really what they were driving at was serialization.
cout << bitset< 8 >( x ) << endl; // print 8 low-order bits of x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With