par*_*c65 6 c++ bits bitwise-operators
我有字节到二进制字符串函数,
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();
}
Run Code Online (Sandbox Code Playgroud)
如何以相同的方式将int写入位?我不想在二进制字符串的开头加上额外的0,这就是为什么我无法弄清楚每次如何创建一个可变长度.另外,我没有使用std :: bitset.
我会发布这个作为答案.它更短,更安全,最重要的是它完成了.
#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();
}
Run Code Online (Sandbox Code Playgroud)
输出:
00000011
更改了功能名称,虽然我对那个不满意......任何人都有个好主意?
像这样的东西应该可以工作(尽管我很快就破解了它,还没有测试):
#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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用 std:bitset 并将任何数字转换为任何大小的位字符串,例如 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;
}
Run Code Online (Sandbox Code Playgroud)