Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting integer to a bit representation

Tags:

c++

int

byte

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.

like image 553
bobber205 Avatar asked Apr 21 '10 21:04

bobber205


People also ask

How do you convert int to bit?

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.

How do you convert an int to a bit in Python?

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 .

Which Java method is used to convert an integer into a binary string?

Java's Integer class has a method named toBinaryString to convert an integer into its binary equivalent string.

What does integer toBinaryString do?

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.


2 Answers

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;
}
like image 186
dcp Avatar answered Oct 17 '22 03:10

dcp


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
like image 37
Potatoswatter Avatar answered Oct 17 '22 04:10

Potatoswatter