Fra*_*ler -2 c++ std binary-data bitset
请考虑以下用于整数类型的代码:
template <class T>
std::string as_binary_string( T value ) {
return std::bitset<sizeof( T ) * 8>( value ).to_string();
}
int main() {
unsigned char a(2);
char b(4);
unsigned short c(2);
short d(4);
unsigned int e(2);
int f(4);
unsigned long long g(2);
long long h(4);
std::cout << "a = " << +a << " " << as_binary_string( a ) << std::endl;
std::cout << "b = " << +b << " " << as_binary_string( b ) << std::endl;
std::cout << "c = " << c << " " << as_binary_string( c ) << std::endl;
std::cout << "d = " << c << " " << as_binary_string( d ) << std::endl;
std::cout << "e = " << e << " " << as_binary_string( e ) << std::endl;
std::cout << "f = " << f << " " << as_binary_string( f ) << std::endl;
std::cout << "g = " << g << " " << as_binary_string( g ) << std::endl;
std::cout << "h = " << h << " " << as_binary_string( h ) << std::endl;
std::cout << "\nPress any key and enter to quit.\n";
char q;
std::cin >> q;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
非常直接,效果很好而且非常简单.
编辑
如何在编译时编写函数来提取任意浮点类型的二进制或位模式?
说到花车我在自己所知的任何现有库中都没有找到类似的东西.我搜索谷歌几天寻找一个,所以我试图编写自己的功能,但没有任何成功.因为我最初问过这个问题所以我不再有可用的代码了,因此我无法准确地向您展示所有不同的实现尝试以及它们的编译器 - 构建错误.我有兴趣尝试在编译期间以通用方式生成浮点数的位模式,并希望将其集成到我现有的类中,无缝地对任何整数类型执行相同的操作.至于浮动类型本身,我已经考虑了不同的格式以及架构端序.对于我的一般用途,浮点类型的标准IEEE版本是我应该关注的所有内容.
当我最初提出这个问题时,iBug建议让我自己写一个函数,而我正试图这样做.我理解二进制数,内存大小和数学,但是当试图将浮点数类型如何存储在内存中时,它们的不同部分{sign bit,base&exp}是我最麻烦的地方.
从那时起,那些给出了很好答案的建议 - 例如,我能够编写一个能够很好地融入我现有的类模板的函数,现在它可以用于我的预期目的.
怎么样自己写一个?
static_assert(sizeof(float) == sizeof(uint32_t));
static_assert(sizeof(double) == sizeof(uint64_t));
std::string as_binary_string( float value ) {
std::uint32_t t;
std::memcpy(&t, &value, sizeof(value));
return std::bitset<sizeof(float) * 8>(t).to_string();
}
std::string as_binary_string( double value ) {
std::uint64_t t;
std::memcpy(&t, &value, sizeof(value));
return std::bitset<sizeof(double) * 8>(t).to_string();
}
Run Code Online (Sandbox Code Playgroud)
如果t浮点数的大小不同,您可能需要更改辅助变量.
您也可以逐位复制它们.这是较慢的,但任意类型的任意.
template <typename T>
std::string as_binary_string( T value )
{
const std::size_t nbytes = sizeof(T), nbits = nbytes * CHAR_BIT;
std::bitset<nbits> b;
std::uint8_t buf[nbytes];
std::memcpy(buf, &value, nbytes);
for(int i = 0; i < nbytes; ++i)
{
std::uint8_t cur = buf[i];
int offset = i * CHAR_BIT;
for(int bit = 0; bit < CHAR_BIT; ++bit)
{
b[offset] = cur & 1;
++offset; // Move to next bit in b
cur >>= 1; // Move to next bit in array
}
}
return b.to_string();
}
Run Code Online (Sandbox Code Playgroud)