如何从C ++中的无符号十六进制获取带符号的int? [英] how to get a signed int from an unsigned hex in C++?

查看:244
本文介绍了如何从C ++中的无符号十六进制获取带符号的int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试搜索几个小时,但是我不知道如何从无符号十六进制中获取负整数.我得到24位十六进制数字,并想要带符号的整数.

I have been trying and searching for hours now but I just don't get how I can get an negative integer from an unsigned hex. I get 24 bit hex numbers and want signed integers.

(为澄清起见,我得到一个以十六进制表示的24位数字.然后,我将其读取为整数,然后将其作为有符号整数给出.)

(to clarify: I get an get a 24 bit number in hexadecimal. Then I read it as an integer and then I want to give it out as a signed integer.)

0xfffef1应该是-271,但我不知道该怎么到达.

0xfffef1 for example should be -271 but I don't know how to get there.

期待一些建议.

我试图反转24位,然后像对二进制文件一样添加一个,但是我也不知道该怎么做.

I have tried to invert the 24bit and then add one like you do with binary but I don't really know how to do that either.

推荐答案

用最高有效字节完成2补码应该可以正常工作:

Completing the 2 complement with the most significant byte should work fine:

#include <iostream>

int main () {

    int a = 0xfffef1;
    a |= 0xff << 24;
    std::cout << a << std::endl;
}

请参见实时演示.

这篇关于如何从C ++中的无符号十六进制获取带符号的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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