Convert integer to bits

家住魔仙堡 提交于 2019-11-30 07:31:16

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?

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;
}

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;
}

Since you mentioned your wish for C style in the comments, you might consider using itoa (or _itoa) if you are not worried about ANSI-C standard. Many compilers support it in stdlib.h. It also strips the leading 0's:

unsigned char yourGoldenNumber = 42;
char binCode[64];
itoa(yourGoldenNumber,binCode,2); // third parameter is the radix
puts(binCode); // 101010
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!