C++将 wwn 字符串转换为识别为十六进制的数据类型
C++ convert wwn string to data type recognized as hex
我正在从事的一个项目已经将 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 产生预期的十六进制值
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 指向存储在字符串 c++ 中的十六进制
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 绝对编码器十六进制输入
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- C++17 十六进制浮点文字单精度后缀冲突?
- 是否可以在C++中获取 CHAR 的有效十六进制地址?
- 打印十六进制字符
- C++将 wwn 字符串转换为识别为十六进制的数据类型