arrayscdata-conversionunsigned-long-long-intbit-representation

How can one store a uint64_t in an array?


I am trying to store a uint64_t representation of a crc64 checksum as an array.

The checksum will always be like uint64_t res = 0x72e3daa0aa188782, so the I want that to be stored as an array, char digest[8], where digest[0] is 72, digest[1] is e3... digest[7] is 82.

I attempted looping/dividing to break up the number, but that would be more appropriate if it was a smaller integer, and if the starting point was Base-10, as the starting point is Base-16, the output should but what is described above.


Update: I removed the nonsensical code and wish I can accept all three answers, as they all did what I asked. The bit shifting is what I was hoping to get as an answer so it is why it is accepted.


Solution

  • Shifting and bit-wise AND can also do what you need. For instance

    unsigned char digest[8];
    int shift = 56;
    for (int i = 0; i < 8; ++i)
    {
        digest[i] = (res >> shift) & 0xff;
        shift -= 8;
    }
    

    If it's okay to change the value of res another approach is:

    for (int i = 7; i >= 0; --i)
    {
        digest[i] = res & 0xff;
        res >>= 8;
    }