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.