HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Char* hex string to BYTE Array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraycharbytehexstring

Problem

The idea is that i want any size string to put the corresponding hex value into a byte array. I've seen a million ways to do it. Some of them didn't look to clean. My needs are speed over memory, so chose to try and implement a lookup table. Tell me what you think

const BYTE HEX[0x80] = //This is the ASCII table in number value form
{   //0     1     2     3     4     5     6    7      8     9     A     B     C     D     E     F
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//0
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//1
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//2
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//3
    0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//4
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//5
    0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,//6
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 //7
};
void ByteUtil::StringToHex(const char* str, BYTE* hex)
{
    int len = strlen(str)/2;
    for(int i=0; i<len; i++)
    {
        hex[i] =  (HEX[*str++] << 4);
        hex[i] += (HEX[*str++]);
    }
}


This method assumes you've already figured out the length of the array. So to use it it would look somethign like this.

char* gky = "55D38577093A88F3B5EA40BBF11158813A2C662EB71FBAB9";
int len = strlen(gky)/2;
BYTE* GKY = new BYTE[len];
ByteUtil::StringToHex(gky, GKY);
ByteUtil::LogArray("GKY", GKY, len);
delete[] GKY;


this particular code snippet outputted this

2013-02-15.10:03:19 GKY(24)- 55:D3:85:77:09:3A:88:F3:B5:EA:40:BB:F1:11:58:81:3A:2C:66:2E:B7:1F:BA:B9:

Solution

Some minor comments:

-
you are assuming there are no invalid chars in the input string.

-
why not pass the string length into the function; the caller has to know it in order to allocate the hex buffer.

-
len could be const

-
unnecessary brackets around RHS expressions in hex[i] assignments

-
I would prefer the second assignment to be |= not +=

-
it is usual to use uppercase names only for #defined constants

Context

StackExchange Code Review Q#22757, answer score: 3

Revisions (0)

No revisions yet.