c++windowshexdata-conversionkernel-mode

Convert char [] of ascii hex digits to unsigned long long (uint64_t)


I've been spending some time on this, and just can't figure out how to convert a character string of hexadecimal digits into an unsigned long long (uint64_t) without using any library routines but only using the shift operator. I need this for a kernel mode driver. I've read this SO post and tried the code given, but it does not produce correct results.

Basically, what I'm trying to do is convert a string like so:

char buffer[] = "FFFFFFFF06749565";

into an unsigned long long (unint64_t) as follows:

0xFFFFFFFF06749565

Solution

  • ntoskrnl.dll export _strtoui64 so you can use this code:

    bool fromstring(_In_ PCSTR str, _Out_ ULONG64& value)
    {
        value = _strtoui64(str, const_cast<char**>(&str), 16);
        return !*str;
    }
    

    if want do this direct (from my view no sense, but as demo only)

    bool fromstring(_In_ PCSTR str, _Out_ ULONG64& value)
    {
        ULONG64 v = 0, n = 17;
    
        do 
        {
            ULONG c = *str++;
    
            if (!c)
            {
                value = v;
                return true;
            }
    
            v <<= 4;
    
            if (c - '0' <= '9' - '0')
            {
                v |= c - '0';
                continue;
            }
            
            if (c - 'A' <= 'F' - 'A')
            {
                v |= c - 'A' + 10;
                continue;
            }
            
            if (c - 'a' <= 'f' - 'a')
            {
                v |= c - 'a' + 10;
                continue;
            }
    
            return false;
    
        } while (--n);
    
        return false;
    }