Search code examples
cwinapitchar

How to concatenate an hex to a string in C


I'm trying to create a string that's composed with multiple parts. It starts as a normal string and at some point a function is called that fills a pointer with an hex number. Like shown below.

PVOID hexval = NULL;
PCTSTR mystring = TEXT("BLA");

function(&hexval);

mystring += hexval;  // just an idea of what I want, not actual code

As shown above I want mystring to have the hexvalue appended to it. Assume my hexvalue is 0x424C41. I want to end with mystring being "BLABLA".

What's the best way to do this?


Solution

  • #include <stddef.h>
    #include <stdlib.h>
    
    #include <windows.h>
    #include <tchar.h>
    
    int main(void)
    {
        ULONG_PTR value  = 0x424C41;
        LPVOID hexval    = &value;
        PCTSTR mystring  = _T("BLA");
    
        size_t length    = _tcslen(mystring);
        size_t new_size  = length + sizeof(ULONG_PTR) + 1;
    
        LPTSTR new_string = calloc(new_size, sizeof(*new_string));
        _tcscpy(new_string, mystring);
    
        size_t offset;
        for (offset = sizeof(ULONG_PTR); offset && !((char*)hexval)[offset - 1]; --offset);
    
        for (size_t i = length ? length : 0, k = offset; k; ++i, --k)
            new_string[i] = ((char*)hexval)[k - 1];
    
        _tprintf(_T("\"%s\"\n"), new_string);
        free(new_string);
    }
    

    Maintaining ANSI-support in 2019 is masochism, though.