十六进制加减法
Hexadecimals adding and subtracting
到目前为止,我有这段代码。当我将两个负整数相加时,答案是肯定的而不是负的。我该如何解决这个问题?我认为0x80000000是整数的最小可能值
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
unsigned int maxInt = 0x7FFFFFFF;
int num1 = 7;
signed int minInt = 0x80000000;
int num2 = -21;
float num3 = 1;
float i;
cout<<"The value of the first variable is: "<<maxInt<<endl;
cout<<"The value of the second variable is: "<< num1<<endl;
cout<<"Addition of the two numbers: "<< maxInt + num1 <<endl;
cout<<endl;
cout<<"The value of the first variable is: "<<minInt<<endl;
cout<<"The value of the second variable is "<<num2<<endl;
cout<<"Addition of the two numbers: "<< minInt + num2 <<endl;
cout<<endl;
system("pause");
return 0;
}
将
0x80000000 和 -21 相加得到的结果是 0x7FFFFFDF。这个十进制的数字是2147483615。发生这种情况是因为最左边的位用于确定符号。你得到一个下溢,在本例中,它环绕到最大整数并从那里倒计时。添加两个正整数应该以另一种方式发生同样的事情,除了它会绕到 0,因为它是无符号的,但是当你溢出或下溢时它是未定义的行为。
正如评论所说,您可以使用更大的类型:
int64_t result = static_cast<int64_t>(maxInt) + num1;
int64_t result2 = static_cast<int64_t>(minInt) - num2;
相关文章:
- 如何在openssl-ecc中获取十六进制格式的私钥
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 为什么mpfr_printf与十六进制浮点(%a转换说明符)的printf不同
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 指向存储在字符串 c++ 中的十六进制
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C ++如何使用UTF8十六进制代码打印UTF8符号?
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何在C++中将十六进制字符串转换为文本数据
- 使用 sprintf 将十六进制0xAABBCC转换为字符串"AA:BB:CC"
- 绝对编码器十六进制输入
- 为什么C++总是显示十六进制内存地址,而不仅仅是整数?
- C++17 十六进制浮点文字单精度后缀冲突?
- 是否可以在C++中获取 CHAR 的有效十六进制地址?
- 打印十六进制字符
- 十六进制加减法