C ASCII to Hex (atoh) Function

136 Views Asked by At

I am looking to develop a function that converts a series of ASCII characters (in their respective hex representation) to a single hex value. For example, an input string to this function may be {0x46 0x32 0x3A 0x42} (or {F 2 0 B} in ASCII), the needed output would be a single integer hex value 0xF20B.

I've tried using type casting, sprintf, and bit operations to develop a function that would do this without success. An approach that I believe would work would be type casting each ASCII Hex value to a char, concatenating them, then converting the string to a single Hex value.

C does have the stdlib.h atof function that converts the input character string to a double precision floating point value. However, this function does not accept characters and so Hex A - F values would not be properly converted.

Thank you in advance for any input.

2

There are 2 best solutions below

0
gulpr On

You can write it yourself:

unsigned long long hexstrtointeger(const char *str)
{
    unsigned long long result = 0;
    char *hex = "0123456789ABCDEF";
    while(*str)
    {
        result *= 0x10;
        char *pos = strchr(hex, toupper(*str++));
        if(pos) result += pos - hex;
    }    
    return result;
}

int main(void)
{
    printf("%llx\n", hexstrtointeger("aB03543Cdf"));
}

https://godbolt.org/z/9s6xn33s8

0
HazyScapes On

Here is where I landed. Hope it helps someone someday. Thank you for your responses.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//Function Declaration
void Function(void)
int atoh(unsigned int ASCII_Data1, unsigned int ASCII_Data2);

void Function(void) {
    unsigned int    Byte1_Data = 0x66;
    unsigned int    Byte2_Data = 0x32;
    unsigned int    HexResult;
    HexResult = atoh(Byte1_Data, Byte2_Data);
    printf("Output of atoh(): 0x%02X\n", HexResult);
    } // End Function
int atoh(unsigned int ASCII_Data1, unsigned int ASCII_Data2) {
    char Byte1_String = (char)ASCII_Data1;
    char Byte2_String = (char)ASCII_Data2;
    char CatHexString[3];
    char *endptr;                                       // Pointer to character after the last valid digit - for use in strtoul
    unsigned long HexData;
    char *HexString;

    CatHexString[0] = Byte1_String;                     // Assign First Character
    CatHexString[1] = Byte2_String;                     // Assign Second Character
    CatHexString[2] = '\0';                             // Add Null Terminator
    printf("Byte1_String: %c and Byte2_String: %c\n", Byte1_String, Byte2_String);
    printf("CatHexString: %s\n", CatHexString);

    HexData = strtoul(CatHexString, &endptr, 16);       // Convert String to Unsigned Long

    return HexData;

} //End atoh()