Neophile
Neophile

Reputation: 5880

CString Hex value conversion to Byte Array

I have been trying to carry out a conversion from CString that contains Hex string to a Byte array and have been

unsuccessful so far. I have looked on forums and none of them seem to help so far. Is there a function with just a few

lines of code to do this conversion?

My code:

BYTE abyData[8];    // BYTE = unsigned char

CString sByte = "0E00000000000400";

Expecting:

abyData[0] = 0x0E;
abyData[6] = 0x04; // etc.

Upvotes: 1

Views: 4200

Answers (3)

Sdra
Sdra

Reputation: 2347

You could:

#include <stdint.h>
#include <sstream>
#include <iostream>

int main() {
    unsigned char result[8];
    std::stringstream ss;
    ss << std::hex << "0E00000000000400";
    ss >> *( reinterpret_cast<uint64_t *>( result ) );
    std::cout << static_cast<int>( result[1] ) << std::endl;
}

however take care of memory management issues!!! Plus the result is in the reverse order as you would expect, so:

result[0] = 0x00
result[1] = 0x04
...
result[7] = 0x0E

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409404

How about something like this:

for (int i = 0; i < sizeof(abyData) && (i * 2) < sByte.GetLength(); i++)
{
    char ch1 = sByte[i * 2];
    char ch2 = sByte[i * 2 + 1];

    int value = 0;

    if (std::isdigit(ch1))
        value += ch1 - '0';
    else
        value += (std::tolower(ch1) - 'a') + 10;

    // That was the four high bits, so make them that
    value <<= 4;

    if (std::isdigit(ch2))
        value += ch1 - '0';
    else
        value += (std::tolower(ch1) - 'a') + 10;

    abyData[i] = value;
}

Note: The code above is not tested.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477444

You can simply gobble up two characters at a time:

unsigned int value(char c)
{
    if (c >= '0' && c <= '9') { return c - '0'; }
    if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }
    if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }

    return -1; // Error!
}

for (unsigned int i = 0; i != 8; ++i)
{
    abyData[i] = value(sByte[2 * i]) * 16 + value(sByte[2 * i + 1]);
}

Of course 8 should be the size of your array, and you should ensure that the string is precisely twice as long. A checking version of this would make sure that each character is a valid hex digit and signal some type of error if that isn't the case.

Upvotes: 3

Related Questions