3

在尝试生成浮点数的位模式时,如下所示:

std::cout << std::bitset<32>(32.5) << std::endl;

编译器生成此警告:

warning: implicit conversion from 'double' to 'unsigned long long' changes value
  from 32.5 to 32 [-Wliteral-conversion]
 std::cout << std::bitset<32>(32.5) << std::endl;

忽略警告时的输出:):

00000000000000000000000000100000

为什么 bitset 不能检测浮点数并正确输出位序列,当转换为 char* 并且步行内存确实显示正确的序列时?这可行,但机器依赖于字节顺序并且大多不可读:

template <typename T>
  void printMemory(const T& data) {
    const char* begin = reinterpret_cast<const char*>(&data);
    const char* end = begin + sizeof(data);
    while(begin != end)
      std::cout << std::bitset<CHAR_BIT>(*begin++) << " ";
    std::cout << std::endl;
}

输出:

00000000 00000000 00000010 01000010 

有理由不支持浮动吗?花车有替代品吗?

4

3 回答 3

3

如果您提供一个浮点数,您希望在您的 bitset 中出现什么?大概是某种以大端格式表示的IEEE-7545 binary32浮点数?那些不代表他们float的 s 的平台怎么办?实现是否应该向后弯曲以(可能有损)将提供的浮点数转换为您想要的?

它没有的原因是没有标准定义的浮点格式。它们甚至不必是 32 位。它们通常在大多数平台上。

C++ 和 C 将在非常小的和/或奇怪的平台上运行。该标准不能指望“通常情况”是什么。有用于 8/16 位 6502 系统的 C/C++ 编译器,对不起,原生浮点格式的借口是(我认为)使用打包 BCD 编码的 6 字节实体。

signed这与不支持整数的原因相同。二进制补码不是通用的,只是几乎通用的。:-)

于 2017-10-20T20:49:38.757 回答
2

关于浮点格式未标准化、字节序等的所有常见警告

这是可能会工作的代码,至少在 x86 硬件上是这样。

#include <bitset>
#include <iostream>
#include <type_traits>
#include <cstring>

constexpr std::uint32_t float_to_bits(float in)
{
    std::uint32_t result = 0;
    static_assert(sizeof(float) == sizeof(result), "float is not 32 bits");
    constexpr auto size = sizeof(float);
    std::uint8_t buffer[size] = {};
    // note - memcpy through a byte buffer to satisfy the
    // strict aliasing rule.
    // note that this has no detrimental effect on performance
    // since memcpy is 'magic'
    std::memcpy(buffer, std::addressof(in), size);
    std::memcpy(std::addressof(result), buffer, size);
    return result;
}

constexpr std::uint64_t float_to_bits(double in)
{
    std::uint64_t result = 0;
    static_assert(sizeof(double) == sizeof(result), "double is not 64 bits");
    constexpr auto size = sizeof(double);
    std::uint8_t buffer[size] = {};
    std::memcpy(buffer, std::addressof(in), size);
    std::memcpy(std::addressof(result), buffer, size);
    return result;
}


int main()
{
    std::cout << std::bitset<32>(float_to_bits(float(32.5))) << std::endl;
    std::cout << std::bitset<64>(float_to_bits(32.5)) << std::endl;
}

示例输出:

01000010000000100000000000000000
0100000001000000010000000000000000000000000000000000000000000000
于 2017-10-20T20:59:47.303 回答
1
#include <iostream>
#include <bitset>
#include <climits>
#include <iomanip>

using namespace std;

template<class T>
auto toBitset(T x) -> bitset<sizeof(T) * CHAR_BIT>
{
    return bitset<sizeof(T) * CHAR_BIT>{ *reinterpret_cast<unsigned long long int *>(&x) };
}

int main()
{
    double x;
    while (cin >> x) {
        cout << setw(14) << x << " " << toBitset(x) << endl;
    }

    return 0;
}

https://wandbox.org/permlink/tCz5WwHqu2X4CV1E

遗憾的是,如果参数类型大于 的大小unsigned long long,则会失败,例如,它将失败long double。这是bitset构造函数的限制。

于 2017-10-20T21:34:56.030 回答