gpt4 book ai didi

C++: bool 值的二进制表示是否有任何保证?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:05:30 25 4
gpt4 key购买 nike

我正在研究 new hashing system .部分实现需要将指向某个内存位置的指针传递到具有如下签名的算法仿函数中:

void
operator()(void const* key, std::size_t len) noexcept
{
unsigned char const* p = static_cast<unsigned char const*>(key);
unsigned char const* const e = p + len;
std::size_t h = 14695981039346656037u;
for (; p < e; ++p)
h = (h ^ *p) * 1099511628211u;
return h;
}

在对基本类型进行操作时,我只是传入一个指向类型开头和大小的指针:

template <class HASHALG>
void hash_append(HASHALG& hashAlg, char const input)
{
hashAlg(&input, sizeof(input));
}

我问 bool 值的二进制表示是否有任何保证的原因是因为我想知道以下是否会按预期运行:

template <class HASHALG>
void hash_append(HASHALG& hashAlg, bool const input)
{
hashAlg(&input, sizeof(input));
}

我担心可能会发生的情况是,编译器可能会选择一个真正的 bool 值可以具有任何非零整数表示。即:

10110010 => true
10101010 => true
10100010 => true
00100010 => true
01100110 => true
00000000 => false

如果是这种情况,则按字节散列是无效的,因为相同的值 (true) 可以产生许多不同的散列。

我已经搜索了标准,我能找到的只有以下两部分:

(3.9.1.7) Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types. A synonym for integral type is integer type. The representations of integral types shall define values by use of a pure binary numeration system.

(4.5.6) A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.

所以我知道 int 将具有整数表示,并且我知道当转换为 int 时,它将是 1 或 0,但是标准是否保证它具有固定的表示?在大多数情况下,编译器似乎只会实现这一点:

true => 00000001
false => 00000000

如果不能保证这将是表示,我不想被一些晦涩的边缘情况所困扰。

最佳答案

除了 char 之外的所有类型都可以有填充位(又名非值位)。
struct 通常甚至有完整的填充字节。
此外,某些类型具有相同值的多种表示形式,而某些类型具有陷阱表示形式。

对于大多数 float ,有许多 NaN 和两个零。
在分段架构中,具有不同表示的指针可能比较相等。

大多数实现将 bool 限制为每个值的一种表示,这有优点也有缺点。 (见过 a!a 都是 false/true 吗?)

因此,您的哈希方法可能不合适...
也许对受影响的原始类型进行预转换?
并显式传递 struct 的所有成员?

关于C++: bool 值的二进制表示是否有任何保证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com