-2

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.

  • What have you tried? What research did you do? Is there really a need for this question? Doesn't the last question hint you how to do it? I even linked a library that implements that conversion - have you studied it? Take a look at https://stackoverflow.com/questions/3784263/converting-an-int-into-a-4-byte-char-array-c . – KamilCuk Mar 13 '21 at 03:15
  • I only glanced at it after learning your example worked, I'll re-read it. – mehmed_ali343 Mar 13 '21 at 03:17
  • Forgive me but what line would that be located on @ https://github.com/biiont/gpsd/blob/master/bits.h#L45 ? – mehmed_ali343 Mar 13 '21 at 03:19
  • Note: `"\xcf\xff\xed\xef\xcf\xff\xed\xed"` is a `char` array of _9_. – chux - Reinstate Monica Mar 13 '21 at 04:07

1 Answers1

2

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.

Joshua
  • 40,822
  • 8
  • 72
  • 132