【问题标题】:C++ how to convert string characters to exact hex bytesC ++如何将字符串字符转换为精确的十六进制字节
【发布时间】:2021-10-18 11:17:32
【问题描述】:

首先:我有一个应用程序,它接受一个字节数组并从中加载程序集。

为了防止(容易)盗版,我的想法是在服务器上保存一个加密字符串,在客户端下载它,解密它以获得例如: std::string decrypted = "0x4D, 0x5A, 0x90, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4";

然后从字符串转换为二进制(字节数组),这样就可以了

uint8_t binary[] = { 0x4D, 0x5A, 0x90, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4 };

然后像以前一样继续,但经过大量谷歌搜索后,我找不到太多关于常规字符串和字节数组之间直接转换的信息。 感谢您的任何帮助! -莎拉

【问题讨论】:

  • 二进制字符串转成字节数组打算执行了吗?
  • 抱歉@Eljay 回答晚了,二进制文件实际上是一个用于嵌入单声道的 DLL 文件!

标签: c++ string hex byte


【解决方案1】:

您可以在循环中使用std::stoi

它为您提供数字的结束位置,然后您可以使用它来检查字符串是否在其末尾,或者它是否是逗号。如果是逗号,请跳过它。然后再次调用std::stoi,使用位置作为要解析的字符串。

这不是最有效的,但应该可以正常工作。

【讨论】:

  • 有趣的想法。虽然我假设我必须让它从有符号整数而不是字节数组加载程序集,因为 stoi 似乎是将字符串转换为有符号整数的函数?除非你能以某种方式从有符号整数中创建一个字节数组..
  • @xSarah 使用std::vector<std::byte>(或std::vector<uint8_t>)并将每个数字附加到它上面。使用向量作为“字节数组”。
【解决方案2】:

首先,你应该去掉“,”。然后您可以逐个字符地解析字符,对每个第二个字符进行按位左移并保存为字节

char firstchar = HexCharToByte('5');
char secondchar = HexCharToByte('D');
char result = firstchar | (secondchar << 4);
printf("%%hhu", result); //93

HexCharToByte 所在位置(仅限大写字符):

char HexCharToByte(char ch) => ch > 57 ? (ch - 55) : (ch - 48);

这是解析十六进制字符的足够快的方法。

【讨论】:

  • 我似乎对如何定义您提供的函数有误解,我也不确定它会多快,因为它是一个非常大的字符串。
  • @xSarah,我想它会比 std::stoi 或其他任何东西都快。我建议了快速解析十六进制字符的方法(仅限大写)。然后你应该做一些基本的工作,比如删除'',','和“0x”来获得只需要的字符..
【解决方案3】:

使用std::stoul 将字符串解释为无符号整数。然后可以将无符号整数转换为 uint8_t 类型。

解析整个字符串的一种方法是使用字符串流。

代码示例:

#include <cstdint>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    // Input string and output vector
    std::string const decrypted{"0x4D, 0x5A, 0x90, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4"};
    std::vector<std::uint8_t> bytes;

    // Parse the string and fill the output vector
    std::istringstream decryptedStringStream{decrypted};
    std::string decryptedElement;
    while (getline(decryptedStringStream, decryptedElement, ','))
    {
        auto const byte = static_cast<std::uint8_t>(std::stoul(decryptedElement, nullptr, 16));
        bytes.push_back(byte);
    }

    // Print the results (in base 10)
    for (auto const &e : bytes)                                                                             
        std::cout << static_cast<int>(e) << '\n';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-23
    • 2018-01-31
    • 2019-07-27
    • 1970-01-01
    • 2023-03-07
    • 2022-06-18
    • 2012-06-05
    • 1970-01-01
    相关资源
    最近更新 更多