Mecanik
Mecanik

Reputation: 1049

C/C++ Convert an array of 8 bytes into a 64-bit integer

In one of my tasks I need to store DWORD into BYTE(s) and then convert them back. Platform is windows only.

I have found the following on this website:

//Convert an array of four bytes into a 32-bit integer.
DWORD getDwordFromBytes(BYTE* b)
{
    return (b[0]) | (b[1] << 8) | (b[2] << 16) | (b[3] << 24);
};

This works for converting 4 bytes into 1 DWORD, however how would you do this for DWORD64 ?

I have tried the following but it's not returning correctly as I am losing data:

DWORD64 getDwordFromBytes64(BYTE* b)
{
    return ((DWORD64)b[0]) | ((DWORD64)b[1] << 8) | ((DWORD64)b[2] << 16) | ((DWORD64)b[3] << 24);
};

Suppose I have a byte array:

BYTE[] = {0x38,0xf0,0x07,0x40,0x01,0x00,0x00,0x00}; //000000014007F038

I need to get 000000014007F038 (DWORD64) back from it correctly.

If someone would give me a solution I would very much appreciate it.

Update:

Upvotes: 0

Views: 4703

Answers (1)

0___________
0___________

Reputation: 67476

if you care about the endianness and do not want to use any pointer or union punning

#define to64b(arr) (((uint64_t)(((uint8_t *)(arr))[7]) <<  0)+\ 
                    ((uint64_t)(((uint8_t *)(arr))[6]) <<  8)+\
                    ((uint64_t)(((uint8_t *)(arr))[5]) << 16)+\
                    ((uint64_t)(((uint8_t *)(arr))[4]) << 24)+\
                    ((uint64_t)(((uint8_t *)(arr))[3]) << 32)+\
                    ((uint64_t)(((uint8_t *)(arr))[2]) << 40)+\
                    ((uint64_t)(((uint8_t *)(arr))[1]) << 48)+\
                    ((uint64_t)(((uint8_t *)(arr))[0]) << 56))

#define to64l(arr) (((uint64_t)(((uint8_t *)(arr))[0]) <<  0)+\ 
                    ((uint64_t)(((uint8_t *)(arr))[1]) <<  8)+\
                    ((uint64_t)(((uint8_t *)(arr))[2]) << 16)+\
                    ((uint64_t)(((uint8_t *)(arr))[3]) << 24)+\
                    ((uint64_t)(((uint8_t *)(arr))[4]) << 32)+\
                    ((uint64_t)(((uint8_t *)(arr))[5]) << 40)+\
                    ((uint64_t)(((uint8_t *)(arr))[6]) << 48)+\
                    ((uint64_t)(((uint8_t *)(arr))[7]) << 56))

uint64_t toUnsigned64(const void *arr, int bigend)
{
    return bigend ? to64b(arr) : to64l(arr);   
}

Upvotes: 5

Related Questions