[英]C++ Reading signed 32-bit integer value
I have a multi-byte primitive type called s32 which I want to read from a byte array. 我有一个称为s32的多字节原始类型,我想从字节数组中读取该类型。
The specifications are: 规格为:
It is a 32-bit signed integer value, stored in little-endian order. 它是一个32位有符号整数值,以little-endian顺序存储。
Negative integers are represented using 2's complement. 负整数使用2的补码表示。
It uses 1 to 5 bytes depending on the magnitude. 根据大小,它使用1到5个字节。 Each byte contributes its low seven bits to the value. 每个字节将其低7位贡献给该值。 If the high (8th) bit is set, then the next byte is also a part of the value. 如果高(第8)位置位,则下一个字节也是该值的一部分。
Sign extension is applied: the seventh bit of the last byte of the encoding is propagated to fill out the 32 bits of the decoded value. 应用符号扩展:编码的最后一个字节的第七位被传播以填充解码值的32位。
In the case of U32 - unsigned 32-bit I come up with this (any comments welcomed!) but not sure how to modify it for S32. 对于U32-无符号32位,我想出了这一点(欢迎任何评论!),但不确定如何为S32对其进行修改。
char temp = 0;
u32 value = 0;
size_t index = 0;
for(int i = 0; i < 5; i++)
{
if(i < 4)
{
temp = 0x7F & buffer[index];
}
else
{
temp = 0x0F & buffer[index];
}
value |= temp << (7 * i);
if(!(0x80 & buffer[index])) break;
++index;
}
Thanks everyone! 感谢大家!
Are you working on a little-endian system? 您正在使用小端系统吗?
If so following should do the trick. 如果是这样,则应采取以下措施。
if(!(0x80 & buffer[index]))
{
if(0x40 & buffer[index]) value = -value;
break;
}
If you need the negative of a little endian value on a big endian system, then it is a bit more tricky, but that requirement would seem very strange to me 如果您需要在大端序系统上使用小端序值的负数,那么它会比较棘手,但是这个要求对我来说似乎很奇怪
I posted a SIGN_EXTEND
macro in an answer to this question . 我在此问题的答案中张贴了SIGN_EXTEND
宏。 For your code, I'd change your u32 value
to s32 value
, and apply SIGN_EXTEND as 为了您的代码,我会改变你的u32 value
到s32 value
,并应用SIGN_EXTEND为
// after loop close
SIGN_EXTEND(value, index * 7, u32);
using the accepted answer for the question, you'd say: 使用问题的公认答案,您会说:
if(value > (1 << (index * 7 - 1))
value -= (1 << (index * 7));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.