Search code examples
carraysintegerbytetypeconverter

How to convert a byte array to a integer?


Lets say I have this byte

uint8_t k[8]= {0,0,0,1,1,1,0,0}; 

Is there a way to get this to become a single integer or hex?


Solution

  • If k represents 8 bytes of the 64-bit integer, go through the array of 8-bit integers, and shift them into the result left-to-right:

    uint64_t res = 0;
    for (int i = 0 ; i != 8 ; i++) {
        res <<= 8;
        res |= k[i];
    }
    

    The direction of the loop depends on the order in which the bytes of the original int are stored in the k array. The above snippet shows the MSB-to-LSB order; if the array is LSB-to-MSB, start the loop at 7, and go down to zero.

    If the bytes represent individual bits, shift by one rather than eight.