Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer to bits

I have byte to binary string function,

std::string byte_to_binary(unsigned char byte)
{
    int x = 128;
    std::ostringstream oss;
    oss << ((byte & 255) != 0);

    for (int i = 0; i < 7; i++, x/=2)
       oss << ((byte & x) != 0);

    return oss.str();
}

How can i write an int to bits in same way? I don't want extra 0's at the beginning of binary string so that is why i can't figure out how to create a variable length each time. Also, i'm not using std::bitset.

like image 609
parc65 Avatar asked May 18 '11 00:05

parc65


People also ask

How many bits is a number 10000?

We have used 14 bits to represent 10000 in binary.

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

Use Python bin to Convert Int to Binary The Python bin() function is short for binary and allows us to convert an integer to a binary string, which is prefixed by '0b' .

How many numbers is 15 bits?

We can count the number of zeros and ones to see how many bits are used to represent 15 in binary i.e. 1111.

How do you convert .75 to binary?

Therefore, the binary equivalent of decimal number 75 is 1001011.


3 Answers

Something like this should work (though I hacked it up quickly and haven't tested):

#include <string>
#include <climits>

template<typename T>
std::string to_binary(T val)
{
  std::size_t sz = sizeof(val)*CHAR_BIT;
  std::string ret(sz, ' ');
  while( sz-- )
  {
    ret[sz] = '0'+(val&1);
    val >>= 1;
  }
  return ret;
}
like image 32
Pablo Avatar answered Sep 24 '22 03:09

Pablo


You can do it using std:bitset and convert any number into bit string of any size, for example 64

#include <string>
#include <iostream>
#include <bitset>
using namespace std;

int main() {

 std::bitset<64> b(836); //convent number into bit array
 std::cout << "836 in binary is " <<  b << std::endl;

 //make it string
 string mystring = b.to_string<char,char_traits<char>,allocator<char> >();
 std::cout << "binary as string " << mystring << endl;
}
like image 22
shirvind Avatar answered Sep 23 '22 03:09

shirvind


I'll just post this as an answer. It is shorter, safer and, what's most important, it is done.

#include <string>
#include <bitset>
#include <type_traits>

// SFINAE for safety. Sue me for putting it in a macro for brevity on the function
#define IS_INTEGRAL(T) typename std::enable_if< std::is_integral<T>::value >::type* = 0

template<class T>
std::string integral_to_binary_string(T byte, IS_INTEGRAL(T))
{
    std::bitset<sizeof(T) * CHAR_BIT> bs(byte);
    return bs.to_string();
}

int main(){
    unsigned char byte = 0x03; // 0000 0011
    std::cout << integral_to_binary_string(byte);
    std::cin.get();
}

Output:

00000011

Changed function name, though I'm not happy with that one... anyone got a nice idea?

like image 59
Xeo Avatar answered Sep 24 '22 03:09

Xeo