带符号的补码算法 [英] signed two's complement arithmetic

查看:33
本文介绍了带符号的补码算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑数据类型范围,出现了一个问题.我们知道有符号字符的范围是从 -128 到 127.我知道 127 是如何来的,即 0111111 = +127

I was thinking on data types ranges, a question arises. As we know signed char's range is from -128 to 127. I got the how 127 comes, i.e. 0111111 = +127

但是我不明白 -128 是怎么来的?如果我们只是 ON 符号位,我们会得到 11111111,它是如何等于 -128 的?

But I could not get how -128 comes? if we just ON sign bit we get 11111111, how its is equal to -128 ?

推荐答案

大多数时候,计算机使用所谓的2 的补码来表示有符号整数.

Most of the time, computers use what's called 2's complement to represent signed integers.

2 的补码的工作方式是可能的值在一个巨大的循环中,从 0 到 MAX_VALUE、MIN_VALUE、零等等.

The way 2's complement works is that the possible values are in a huge loop, from 0, to MAX_VALUE, to MIN_VALUE, to zero, and so on.

所以最小值是最大值+1 - 01111111 = 127,而10000000 = -128.

So the minimum value is the maximum value +1 - 01111111 = 127, and 10000000 = -128.

这具有与无符号算术完全相同的良好特性 - 如果我想做 -2 + 1,我有 11111110 + 00000001 = 11111111 = -1>,使用与无符号加法相同的硬件.

This has the nice property of behaving exactly the same as unsigned arithmetic - if I want to do -2 + 1, I have 11111110 + 00000001 = 11111111 = -1, using all the same hardware as for unsigned addition.

在低端有一个额外值的原因是我们选择将所有高位设置为负数,这意味着 0 从正侧取值.

The reason there's an extra value on the low end is that we choose to have all numbers with the high-bit set be negative, which means that 0 takes a value away from the positive side.

这篇关于带符号的补码算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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