Search code examples
ctype-conversion64-bitunsigned-charunsigned-long-long-int

How to convert unsigned long long int into unsigned char*?


Say for instance I have this unsigned long long int:

unsigned long long int test_int = 0xcfffedefcfffeded; // 14987959699154922989

How could I convert test_int into the following unsigned char* array:

unsigned char test_char[] = "\xcf\xff\xed\xef\xcf\xff\xed\xed";

Similar to this question I asked: How to convert unsigned char* to unsigned long long int? The only exception is being in reverse.


Solution

  • Inline conversion (endian-indpendent) with bit shifts

    char test_char[8];
    test_char[0] = (char)(unsigned char)(test_int >> 56);
    test_char[1] = (char)(unsigned char)(test_int >> 48);
    test_char[2] = (char)(unsigned char)(test_int >> 40);
    test_char[3] = (char)(unsigned char)(test_int >> 32);
    test_char[4] = (char)(unsigned char)(test_int >> 24);
    test_char[5] = (char)(unsigned char)(test_int >> 16);
    test_char[6] = (char)(unsigned char)(test_int >> 8);
    test_char[7] = (char)(unsigned char)(test_int);
    

    Bonus: we don't need to talk about alignment or endianness. This just works.

    As has been pointed out in the comments, test_char in the question has a trailing null terminator, which we can also do by setting char test_char[9]; and test_char[8] = 0;; however when this question comes up in practice, the real example rarely has a terminating null nor would it make sense because of nulls in the middle.

    Commentary: I wish there was a standard htonq for this, but there isn't.