2017-10-13 80 views
0

我正在写的整体式为一个字节数组这样的:提取从字节数组积分型

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 

在这种情况下,是的numBytes实际写入到所述阵列的字节数,这可改变 - 有时我会写一个短的,有时INT等

在测试情况下,我知道的numBytes == 2,本工程以获取积分值:

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

在此基础上, 一世试图做同样的用长长的,所以它会工作为任意整数类型:

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

但当整数< 0我很感激,如果有人能指出我什么,失败在这里失踪。我省略了符号位?我如何确保这是以便携方式包含的?

干杯!

+0

给出一个失败的特定情况(即'NumBytes'的值,'Data [0 ... NumBytes-1]'的内容,您实际获得的Integer的值以及您想要的值。 ) –

+0

为什么不使用memcpy呢? –

+0

似乎可以使用负值正常工作:https://ideone.com/ABvMM8 您可以详细说明编译器/系统吗? – mnistic

回答

1

这工作:

#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; 
} 

当您打开短到长,只要你在你的代码一样,符号位变成了长长的最显著位,这意味着要正确编码/解码它需要全部8个字节。

+0

对,所以当我截断一个更大的整型时,符号位是我失去的第一个东西。我试图做的事情是尽量减少网络使用的字节数,所以我不得不重新考虑这一点。谢谢你帮助我理解! –