简体   繁体   中英

C++ how to convert string characters to exact hex bytes

To start off: I have an app that takes a byte array and loads assembly from it.

My idea, to prevent (easy)piracy, was to have an encrypted string on server, download it on client, decrypt it to get for example: std::string decrypted = "0x4D, 0x5A, 0x90, 0x0, 0x3, 0x0, 0x0, 0x0, 0x4";

Then to convert from string to binary(byte array) so it would be

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

And then continue as it was before, but after lots of googling I couldn't find much info on such direct conversion between regular string and byte array. Thank you for any help! -Sarah

You could use std::stoi in a loop.

It gives you the ending position of the number, which you can then use to check if the string is at its end, or if it's a comma. If it's a comma skip it. Then call std::stoi again using the position as the string to parse.

It's not the most effective, but should work fine.

Use std::stoul to interpret a string as an unsigned integer. The unsigned integer can then be cast to a uint8_t type.

One method of parsing the entire string is by using a stringstream.

Code example:

#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';
}

First of all, you should get rid of ", ". Then you can parse char by char, doing bitwise leftshift on every second char and saving as byte

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

Where HexCharToByte is (upper chars only):

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

This is fast enough method of parsing hex chars.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM