문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

This should do the trick:

int convertToInt(uint8_t k[8], bool leastSignificantFirst) { 
    int res = 0;
    for (int i = 0; i < 8; ++i) { 
        if (leastSignificantFirst) { 
            res |= (k[i] & 1) << (7 - i);
        } else {
            res |= (k[i] & 1) << i;
        }
    }
    return res;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top