Search code examples
cbit-manipulationbit

reverse hex number into a string


I want to convert unsigned long long

0xabcd1234

to this string

3412cdab

*we want to keep leading zeroes so for example 0x1 will convert to this string "01000000" and 0x123 to "23010000"

now I succeded in writing code that does that but I wonder if there is a much simpler way

char* encode_long_long_hex(unsigned long long integer, char* out, 
                           int  len, size_t *out_len)
{
    static char encode_hex_char_arr[] = {
        '0', '1', '2', '3', '4', '5', '6', '7',  
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };

    char* dst = out;
    unsigned idx = count_long_long_digits(integer); //return number of digits
    
    while (idx && dst < out + len)
    {
        idx -= 2;
        
        *dst = encode_hex_char_arr[(integer & 0xF0) >> 4];
        dst += sizeof(char);
        
        *dst = encode_hex_char_arr[integer & 0x0F];
        dst += sizeof(char);
        
        integer >>= 8;
    }

    *out_len = (int) (dst - out);
    
    return dst;
}

Thanks!


Solution

  • I'm guessing the formal question you are asking is "how do I convert an int represented as hex from big-endian to little-endian" (or vice-versa)

    If so then the formal answer would be "parse the hex, convert the endianess, format back to hex", or in other words format(convert(parse(input))), or in C:

    #include <stdlib.h>
    #include <byteswap.h>
    #include <stdio.h>
    
    char output[11];
    sprintf(output, "0x%x", bswap_32(strtol(input, NULL, 0)));
    
    // Or without "0x" in both input and output:
    
    char output[9];
    sprintf(output, "%x", bswap_32(strtol(input, NULL, 16)));