C++将 wwn 字符串转换为识别为十六进制的数据类型

C++ convert wwn string to data type recognized as hex

本文关键字:识别 十六进制 数据类型 转换 wwn 字符串 C++      更新时间:2023-10-16

我正在从事的一个项目已经将 iscsi 设备的 wwn 存储为 std::string 减去冒号。 我必须获取字符串的一个子集并将它们 XOR 或者,就好像它们是字节一样,具有另一组字节,用于 scsi 命令安全代码。 我也应该转换哪种数据类型的字符,以便 XOR 将它们视为十六进制字节。 这些数字已经正是我所需要的,但编译器会将它们解释为 ASCII。 我只需要一种方法来告诉编译器这些已经是十六进制字节。

字符串是 601ad142,所以我也需要转换它 [0x60、0x1a、0xd1、0x42],这样我就可以用 [0x57、0x68、0x6f、0x61] 对每个字节进行异或

如果我可以将 wwn 字符串:600601601ad14200b9265b5b274efb84(已在现有代码中提供(转换为uinit64_t我也可以使用它,但是:

std::string wwid(path.wwid);
wwid.erase(std::remove(wwid.begin(), wwid.end(), ':'), wwid.end());//remove colons
uint64_t wwn = wwid
std::istringstream strWwid(wwid);
strWwid >> wwn;

返回0x23cc7401

更新:我找到了一个可行的解决方案。

std::string wwid(path.wwid);
wwid.erase(std::remove(wwid.begin(), wwid.end(), ':'), wwid.end());
char wwnBytes[8];
strncpy( wwnBytes, wwid.c_str() + 6, 8); // get chars for bytes 4 -7
std::string bytes = wwnBytes;
std::stringstream ss;
unsigned int secBytes;
ss << std::hex << bytes;
ss >> secBytes; 

十六进制是一种文本表示 –{0x60, 0x1a, 0xd1, 0x42}{96, 26, 209, 66}相同。

您的字符串包含这些字符('6''0'等(的 (ASCII( 表示形式,您需要将它们转换为它们所表示的数字。

对于一个角色,类似

// Assumes that c is an ASCII-encoded hexadecimal digit.
// TODO: Add input validation.
unsigned int from_hex(char c)
{
return (c <= '0' && c <= '9') 
? c - '0'
: 10 + std::toupper(c) - 'A';
}

要将两位数转换为字节值,您可以使用

unsigned int from_hex(char hi_bits, char lo_bits)
{
return from_hex(hi_bits) * 16 + from_hex(lo_bits);
}

然后from_hex('6', 'f')将产生一百一十一,用十六进制写成 6f。

我能够使用 std::stringstream 做到这一点:

std::string wwid(path.wwid);
wwid.erase(std::remove(wwid.begin(), wwid.end(), ':'), wwid.end());
char wwnBytes[8];
strncpy( wwnBytes, wwid.c_str() + 6, 8); // get chars for bytes needed
std::string bytes = wwnBytes;
std::stringstream ss;
unsigned int secBytes;
ss << std::hex << bytes;
ss >> secBytes; // bytes 4-7 in hex

生成的无符号 int 产生预期的十六进制值