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.
Inline conversion (endian-indpendent) with bit shifts
Bonus: we don't need to talk about alignment or endianness. This just works.
As has been pointed out in the comments,
test_charin the question has a trailing null terminator, which we can also do by settingchar test_char[9];andtest_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
htonqfor this, but there isn't.