使用C ++将四个字节转换为Integer [英] Convert four bytes to Integer using C++

查看:60
本文介绍了使用C ++将四个字节转换为Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C ++将4个字节转换为整数.

I am trying to convert 4 bytes to an integer using C++.

这是我的代码:

int buffToInteger(char * buffer)
{
    int a = (int)(buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3]);
    return a;
}

上面的代码在几乎所有情况下都适用,例如:当我的缓冲区是:"[\ x00,\ x00,\ x40,\ x00]" 时,代码将按预期返回 16384 .

The code above works in almost all cases, for example: When my buffer is: "[\x00, \x00, \x40, \x00]" the code will return 16384 as expected.

但是当缓冲区中充满:"[\ x00,\ x00,\ x3e,\ xe3]" 时,该代码将无法正常工作,并且将返回"ffffffe1".

But when the buffer is filled with: "[\x00, \x00, \x3e, \xe3]", the code won't work as expected and will return "ffffffe1".

有人知道为什么会这样吗?

Does anyone know why this happens?

推荐答案

您的 buffer 包含 signed 个字符.因此,实际上是 buffer [0] == -29 ,在转换为 int 后,它会被符号扩展为 0xffffffe3 ,然后<代码>(0x3e<< 8)|0xffffffe3 == 0xffffffe3 .

Your buffer contains signed characters. So, actually, buffer[0] == -29, which upon conversion to int gets sign-extended to 0xffffffe3, and in turn (0x3e << 8) | 0xffffffe3 == 0xffffffe3.

您需要通过将 buffer 声明为 unsigned char * ,确保将各个 buffer 字节解释为 unsigned ,或通过显式强制转换:

You need ensure your individual buffer bytes are interpreted unsigned, either by declaring buffer as unsigned char *, or by explicitly casting:

int a = int((unsigned char)(buffer[0]) << 24 |
            (unsigned char)(buffer[1]) << 16 |
            (unsigned char)(buffer[2]) << 8 |
            (unsigned char)(buffer[3]));

这篇关于使用C ++将四个字节转换为Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆