gpt4 book ai didi

c++ - 长十六进制值的 vector

转载 作者:行者123 更新时间:2023-12-02 09:52:41 27 4
gpt4 key购买 nike

在C++中,我可以使用

std::vector<uint8_t> data = {0x01, 0x02, 0x03};
为了方便起见(我有自然在十六进制转储中输出的python字节字符串),我想初始化为以下形式的无界十六进制值:
std::vector<uint8_t> data = 0x229597354972973aabbe7;
是否存在有效的c++变体?

最佳答案

结合Evg,JHbonarius和1201ProgramAlarm的评论:
答案是,没有直接的方法可以将长的十六进制值分组为 vector ,但是,使用user defined literals可提供巧妙的符号改进。
首先,在代码中的任何地方使用RHS 0x229597354972973aabbe7都会失败,因为假定未加后缀的文字为int类型,并且将无法包含在寄存器中。在MSVC中,导致E0023“整数常数太大”。带有后缀的表示法可能会限制为较小的十六进制序列或浏览大型数据类型,但这会破坏任何对简单性的要求。
手动转换是必需的,但是用户定义的文字可能会提供稍微更优雅的表示法。例如,我们可以将十六进制序列转换为带有

std::vector<uint8_t> val1 = 0x229597354972973aabbe7_hexvec;
std::vector<uint8_t> val2 = "229597354972973aabbe7"_hexvec;
使用以下代码:
#include <vector>
#include <iostream>
#include <string>
#include <algorithm>


// Quick Utlity function to view results:
std::ostream & operator << (std::ostream & os, std::vector<uint8_t> & v)
{
for (const auto & t : v)
os << std::hex << (int)t << " ";

return os;
}

std::vector<uint8_t> convertHexToVec(const char * str, size_t len)
{
// conversion takes strings of form "FFAA54" or "0x11234" or "0X000" and converts to a vector of bytes.

// Get the first two characters and skip them if the string starts with 0x or 0X for hex specification:
std::string start(str, 2);
int offset = (start == "0x" || start == "0X") ? 2 : 0;

// Round up the number of groupings to allow for ff_hexvec fff_hexvec and remove the offset to properly count 0xfff_hexvec
std::vector<uint8_t> result((len + 1 - offset) / 2);

size_t ind = result.size() - 1;

// Loop from right to left in in pairs of two but watch out for a lone character on the left without a pair because 0xfff_hexvec is valid:
for (const char* it = str + len - 1; it >= str + offset; it -= 2) {
int val = (str + offset) > (it - 1); // check if taking 2 values will run off the start and use this value to reduce by 1 if we will
std::string s(std::max(it - 1, str + offset), 2 - val);
result[ind--] = (uint8_t)stol(s, nullptr, 16);
}

return result;
}

std::vector<uint8_t> operator"" _hexvec(const char*str, std::size_t len)
{
// Handles the conversion form "0xFFAABB"_hexvec or "12441AA"_hexvec
return convertHexToVec(str, len);
}

std::vector<uint8_t> operator"" _hexvec(const char*str)
{
// Handles the form 0xFFaaBB_hexvec and 0Xf_hexvec
size_t len = strlen(str);
return convertHexToVec(str, len);
}

int main()
{
std::vector<uint8_t> v;

std::vector<uint8_t> val1 = 0x229597354972973aabbe7_hexvec;
std::vector<uint8_t> val2 = "229597354972973aabbe7"_hexvec;

std::cout << val1 << "\n";
std::cout << val2 << "\n";

return 0;
}
编码人员必须决定这是否优于实现和使用更传统的 convertHexToVec("0x41243124FF")函数。

关于c++ - 长十六进制值的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63197844/

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