簡體   English   中英

C++ 如何將字符串字符轉換為精確的十六進制字節

[英]C++ how to convert string characters to exact hex bytes

首先:我有一個應用程序需要一個字節數組並從中加載程序集。

為了防止(容易)盜版,我的想法是在服務器上有一個加密的字符串,在客戶端下載它,解密它以獲得例如: std::string decrypted = "0x4D, 0x5A, 0x90, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4";

然后從字符串轉換為二進制(字節數組),這樣就可以了

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

然后像以前一樣繼續,但經過大量谷歌搜索后,我找不到太多關於常規字符串和字節數組之間直接轉換的信息。 感謝您的任何幫助! -莎拉

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

它為您提供數字的結尾 position,然后您可以使用它來檢查字符串是否在其末尾,或者它是否為逗號。 如果是逗號,請跳過它。 然后使用 position 作為要解析的字符串再次調用std::stoi

它不是最有效的,但應該可以正常工作。

使用std::stoul將字符串解釋為無符號 integer。然后可以將無符號 integer 轉換為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';
}

首先,你應該擺脫“,”。 然后你可以逐個解析一個字符,對每個第二個字符進行按位左移並保存為字節

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);

這是解析十六進制字符的足夠快的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM