你是否可以拥有浮点数据类型的bitset容器?例如:
bitset<sizeof(float)*sizeof(char)> second(5.5f);
cout << second.to_string() << endl;
它不能正确地工作。我想做的是获取比特表示。
bitset<sizeof(float)*sizeof(char)> second(5.5f);
cout << second.to_string() << endl;
它不能正确地工作。我想做的是获取比特表示。
bitset
只接受unsigned long
类型作为构造函数参数。在你的例子中,float
被转换为unsigned long
,然后用作参数。
如果你想得到你想要的结果,可以使用以下方式:
float f = 5.5f;
std::bitset<sizeof(float)*CHAR_BIT> foo(*reinterpret_cast<unsigned long*>(&f));
float
构建 bitset
,您应该:
float
的表示复制到一个兼容的整数中;bitset
。#include <bitset>
#include <cstring>
float f = 1.618;
static_assert(sizeof(float) <= sizeof(long long unsigned int), "wrong sizes"); // 1.
long long unsigned int f_as_int = 0;
std::memcpy(&f_as_int, &f, sizeof(float)); // 2.
std::bitset<8*sizeof(float)> f_as_bitset{f_as_int}; // 3.
然而,在一个大端字节序的目标机器上,如果long long unsigned int
比float
更大,则这种方法不会按预期工作,因为无论字节序如何,位集构造函数始终选择参数的最低有效位。这很糟糕。
所以,如果我们想要完整的解决方案,就需要解决这个问题。为了做到这一点,可以将浮点数复制到相同大小的整数中(2.),然后将其强制转换(3.)为long long unsigned int
,从而得到一个与字节序无关的表示。但是,确实需要费力地处理字节序无关的解决方案:
#include <bitset>
#include <cstring>
#include <cstdint>
#include <iostream>
namespace details
{
template<unsigned nbits> struct uint {};
template<> struct uint<8> { using type = uint8_t; };
template<> struct uint<16> { using type = uint16_t; };
template<> struct uint<32> { using type = uint32_t; };
template<> struct uint<64> { using type = uint64_t; };
}
template<class T>
using unsigned_integer_of_same_size = typename details::uint<sizeof(T)*8>::type;
int main()
{
float f = -1./0.;
static_assert(sizeof(float) <= sizeof(long long unsigned int), "wrong sizes"); // 1.
unsigned_integer_of_same_size<float> f_as_uint = 0;
std::memcpy(&f_as_uint, &f, sizeof(float)); // 2.
std::bitset<8*sizeof(float)> f_as_bitset{f_as_uint}; // 3. && 4.
std::cout << f_as_bitset << "\n";
}
long long unsigned int
比 float
大,则无法正常工作,因为它会将浮点位复制到整数的位集中,这些位在构造位集时被丢弃。 - Mark Busing int_type = unsigned_integer_of_same_size<float>; std::bitset<8*sizeof(float)> f_as_bitset{*(int_type*)(&f)};
- qed
sizeof(char)
没有意义。根据 定义,char
的大小为一。 - John Diblingsizeof(float)*CHAR_BIT
。(参见这里)。 - Robᵩ