C++读取带符号的 32 位整数值
我有一个名为 s32 的多字节原始类型,我想从字节数组中读取它。
规范为:
它是一个 32 位有符号整数值,以小端序存储。
负整数使用 2 的补码表示。
根据大小,它使用 1 到 5 个字节。每个字节将其低七位贡献给该值。如果设置了高位(第 8 位),则下一个字节也是该值的一部分。
应用符号扩展:编码最后一个字节的第七位被传播以填充解码值的 32 位。
对于 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;
}
谢谢大家!
I have a multi-byte primitive type called s32 which I want to read from a byte array.
The specifications are:
It is a 32-bit signed integer value, stored in little-endian order.
Negative integers are represented using 2's complement.
It uses 1 to 5 bytes depending on the magnitude. Each byte contributes its low seven bits to the value. If the high (8th) bit is set, then the next byte is also a part of the value.
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.
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.
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用小端系统吗?
如果是这样,下面应该可以解决问题。
如果您需要大端系统上的小端值的负数,那么这就有点棘手,但这个要求对我来说似乎很奇怪
Are you working on a little-endian system?
If so following should do the trick.
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. For your code, I'd change youru32 value
tos32 value
, and apply SIGN_EXTEND asusing the accepted answer for the question, you'd say: