C++ 从字节数组中提取整数类型

C++ 从字节数组中提取整数类型,c++,C++,我正在向字节数组写入一个整数类型,如下所示: 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 无符号字符数据[10];//字节数组

我正在向字节数组写入一个整数类型,如下所示:

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
无符号字符数据[10];//字节数组示例
有符号长整数=1283318;//任意值
对于(int i=0;i>(i*8))&0xff;//设置字节
在这个上下文中,NumBytes是实际写入数组的字节数,它可以改变-有时我会写一个短的,有时是一个int,等等

在我知道NumBytes==2的测试用例中,这用于检索整数值:

signed short Integer = (Data[0] << 0) | (Data[1] << 8);
signed short Integer=(数据[0]此操作:

#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;
}
#包括
使用名称空间std;
int main(){
有符号短输入=-288;
int NumBytes=sizeof(有符号长);
无符号字符数据[10];//字节数组示例
有符号长整数=输入;//任意值
std::cout(i*8))&0xff;//设置字节
有符号长整数2=0;
对于(int i=0;iInteger2 |=static|u cast(Data[i])给出失败的具体情况(即
NumBytes
的值、
Data[0…NumBytes-1]的内容、实际得到的
Integer
的值和所需的值)为什么不改为使用memcpy?似乎可以处理负值:您能给出编译器/系统的详细信息吗?@mnistic在该示例中,它可以使用NumBytes==8。当您使用无符号短字符作为输入,且NumBytes变为2时,它就不再工作了。如右图所示,只要我截断一个较大的整数类型,符号位就是第一位我失去的东西。我想做的事情是尽量减少网络使用的字节数,所以我必须重新考虑。谢谢你帮助我理解!
#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;
}