For example I have string that contains hexadecimal numbers:
std::string hexStr = "E110A3" and I want to convert it to char.
So that char hex[3] = {0xE1, 0x10, 0xA3}
How I can accomplish this?
I tried to search but I didn't find answer to this.

Dani AI

Generated

Good instinct from : split the string into 2-digit chunks and turn each pair into one byte. Two practical gotchas to keep this robust: (1) validate that the input length is even and all characters are hex digits; (2) avoid storing raw bytes in char if you can, because char may be signed and values like 0xE1 can appear negative on some platforms. Prefer unsigned char or std::uint8_t, and only cast to char at the boundary if you truly need a char[].

#include <string_view>
#include <vector>
#include <stdexcept>

std::vector<unsigned char> hex_to_bytes(std::string_view s) {
    if (s.size() % 2 != 0) throw std::invalid_argument("odd-length hex string");

    auto hex = [](unsigned char c) -> int {
        if ('0' <= c && c <= '9') return c - '0';
        c |= 0x20;                 // fold 'A'..'F' to 'a'..'f'
        if ('a' <= c && c <= 'f') return c - 'a' + 10;
        return -1;                 // not a hex digit
    };

    std::vector<unsigned char> out;
    out.reserve(s.size() / 2);

    for (size_t i = 0; i < s.size(); i += 2) {
        int hi = hex(static_cast<unsigned char>(s[i]));
        int lo = hex(static_cast<unsigned char>(s[i + 1]));
        if (hi < 0 || lo < 0) throw std::invalid_argument("non-hex digit");
        out.push_back(static_cast<unsigned char>((hi << 4) | lo));
    }
    return out;
}

// example:
// auto bytes = hex_to_bytes("E110A3");  // {0xE1, 0x10, 0xA3}

If you absolutely need char hex[3], you can fill it from the result with static_cast<char>(bytes[i]), understanding the signedness caveat. On modern compilers (C++17+), another tidy option is to parse each 2-character slice with std::from_chars(..., 16) and verify the conversion consumed exactly two digits, but the nibble approach above is fast, dependency-free, and works back to much older standards.

Recommended Answers

All 4 Replies

For example I have string that contains hexadecimal numbers:
std::string hexStr = "E110A3" and I want to convert it to char.
So that char hex[3] = {0xE1, 0x10, 0xA3}
How I can accomplish this?
I tried to search but I didn't find answer to this.

You need to first extract the two digit pairs from the string. Then you need to write a function that takes a two character string, representing a hexadecimal byte value and turn it into a number from 0 to 255 (does a char with a value over 127 have meaning?)

char Convert (string hexNumber)
// assumes 2 character string with legal hex digits
{
     char aChar;
     char highOrderDig = hexNumber[0];
     char lowOrderDig  = hexNumber[1];
     int lowOrderValue = //;  convert lowOrderDig to number from 0 to 15
     int highOrderValue = //; convert highOrderDig to number from 0 to 15
     aChar = lowOrderValue + 16 * highOrderValue;
     return aChar;
}

That's how I'd do it.

Thanks for quick reply.
I try this as I get home.

What is the best way to convert char to int (as you described low order to int 0-15)?
First thing that comes in my mind is to use if statements but that seems pretty stupid way.
Eg.
if(lowOrder = 'A') number = 10;

Thanks for quick reply.
I try this as I get home.

What is the best way to convert char to int (as you described low order to int 0-15)?
First thing that comes in my mind is to use if statements but that seems pretty stupid way.
Eg.
if(lowOrder = 'A') number = 10;

You would want == rather than = in the line above. The above would work but it would require that you have at least 16 if statement comparisons possibly, which is excessive. Take a look at the ASCII table.

http://www.asciitable.com/

You have three possibilities (assuming legal data). One, the character is 0 through 9. Two, the character is A - F (upper case). Three, the character is a - f (lower case). Anything else is illegal. Regarding the upper versus lower case, you can also either assume the character is upper case, or you can convert to upper case. The cctype library can be useful for this:

In particular, for your case, the following functions could be useful : toupper, isupper, isdigit, isalpha.

You do not NEED to use any of these functions however. You can instead convert directly using the ASCII code. To do so, figure out what the ascii offset would be. In the case of 'A' through 'F', the ascii offset would be 55. If you do use the cctype functions, you would not necessarily need to hard-code in these ASCII values.

int GetDigitValue (char digit)
{
     int asciiOffset, digitValue;
     if (digit >= 48 && digit <= 57)
     {
           // code for '0' through '9'
     }
     else if (digit >= 65 && digit <= 70)
     {
          // digit is 'A' through 'F'
          asciiOffset = 55;
          digitValue = digit - asciiOffset;
          return digitValue;
     }
     else if (digit >= ? && digit <= ?)
     {
           // code for 'a' through 'f'
     }
     else
     {
           // illegal digit
     }
}

You can also use an if-statement like this:

if (digit >= 'A' && digit <= 'F')

Thanks it's working perfectly!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.