gpt4 book ai didi

c++ - 将数组中的字节添加到单个值中,将无符号字节添加到 uint64

转载 作者:行者123 更新时间:2023-12-02 03:25:25 26 4
gpt4 key购买 nike

//glues bytes together, into 64bit
UINT64 AppendBytes64(uint8_t* val, int start)
{
UINT64 result = 0;
result = (val[start+0] << 0) | (val[start + 1] << 8) | (val[start + 2] << 16) | (val[start + 3] << 24) | (val[start + 4] << 32) | (val[start + 5] << 40) | (val[start + 6] << 48) | (val[start + 7] << 56);
return result;
}

所以问题是 Visual Studio 不断警告算术溢出、左移计数大于操作数大小,请帮忙。

最佳答案

Implicit integral promotion

prvalues of small integral types (such as char) may be converted to prvalues of larger integral types (such as int). In particular, arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.

为了避免隐式转换,您必须自己使用 C++ explicit type conversion 转换为合适的类型。以及无符号 64 位整数的标准类型 std::uint64_t 以及用于索引的无符号类型 std::size_t,它应该如下所示:

#include <cstddef>
#include <cstdint>

using std::uint64_t;

constexpr uint64_t AppendBytes64(const uint8_t* val, std::size_t start) {
return static_cast<uint64_t>(val[start + 0]) << 0 |
static_cast<uint64_t>(val[start + 1]) << 8 |
static_cast<uint64_t>(val[start + 2]) << 16 |
static_cast<uint64_t>(val[start + 3]) << 24 |
static_cast<uint64_t>(val[start + 4]) << 32 |
static_cast<uint64_t>(val[start + 5]) << 40 |
static_cast<uint64_t>(val[start + 6]) << 48 |
static_cast<uint64_t>(val[start + 7]) << 56;
}

constexpr 使得可以在常量表达式中使用该函数,从 C++11 及以后版本中获取编译时常量(给定 constexpr 输入)。

关于c++ - 将数组中的字节添加到单个值中,将无符号字节添加到 uint64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60738694/

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