我正在写的整体式为一个字节数组这样的:提取从字节数组积分型
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我很感激,如果有人能指出我什么,失败在这里失踪。我省略了符号位?我如何确保这是以便携方式包含的?
干杯!
给出一个失败的特定情况(即'NumBytes'的值,'Data [0 ... NumBytes-1]'的内容,您实际获得的Integer的值以及您想要的值。 ) –
为什么不使用memcpy呢? –
似乎可以使用负值正常工作:https://ideone.com/ABvMM8 您可以详细说明编译器/系统吗? – mnistic