简体   繁体   中英

extracting integral type from byte array

I'm writing an integral type to a byte array like this:

unsigned char Data[10]; // Example byte array
signed long long Integer = 1283318; // arbitrary value
for (int i = 0; i < NumBytes; ++i)
    Data[i] = (Integer >> (i * 8)) & 0xff; // Set the byte

In this context, NumBytes is the number of bytes actually being written to the array, which can change - sometimes I'll be writing a short, sometimes a int, etc.

In a test case where I know NumBytes == 2, this works to retrieve the integral value:

signed short Integer = (Data[0] << 0) | (Data[1] << 8);

Based on this, I tried to do the same with a long long, so it would work for an arbitrary integral type:

signed long long Integer = 0;
for (int i = 0; i < NumBytes; ++i)
    Integer |= static_cast<signed long long>(Data[i]) << (i * 8);

But, this fails when Integer < 0. I'd be thankful if someone could point out what I'm missing here. Am I omitting the sign bit? How would I make sure this is included in a portable way?

Cheers!

This works:

#include <iostream>

using namespace std;

int main() {
    signed short Input = -288;
    int NumBytes = sizeof(signed long long);

    unsigned char Data[10]; // Example byte array
    signed long long Integer = Input; // arbitrary value
    std::cout << Integer << std::endl;
    for (int i = 0; i < NumBytes; ++i)
        Data[i] = (Integer >> (i * 8)) & 0xff; // Set the byte
    signed long long Integer2 = 0;
    for (int i = 0; i < NumBytes; ++i)
        Integer2 |= static_cast<signed long long>(Data[i]) << (i * 8);
    std::cout << Integer2 << std::endl;
    return 0;
}

When you turn the short into the long long as you did in your code, the sign bit becomes the most significant bit in the long long, which means to correctly encode / decode it you need the all 8 bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM