将整数转换为位 [英] Convert integer to bits

查看:70
本文介绍了将整数转换为位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字节转二进制字符串的功能,

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

我如何以相同的方式将int写入位?我不希望二进制字符串的开头有额外的0,这就是为什么我每次都不知道如何创建可变长度的原因. 另外,我没有使用std :: bitset.

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.

推荐答案

我将其发布为答案.它更短,更安全,最重要的是,它 完成 .

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

输出:

00000011

00000011

更改了函数名,尽管我对此感到不满意...任何人都有一个好主意?

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

这篇关于将整数转换为位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆