本文介绍了Java中负整数的二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我理解负整数的二进制表示。

Please, help me to understand binary presentation of negative integers.

例如我们有5.
5的二进制表示 00000000.00000000.00000000.00000101

据我所知,-5的二进制表示应该像 10000000.00000000.00000000.00000101

And as I understand binary presentation of -5 should be like 10000000.00000000.00000000.00000101.

但输出 11111111.11111111.11111111.11111011

我有2个问题:

1)为什么这么多 1 位。

1) Why here is so much 1 bits.

2)我真的无法理解它最后3位 011 。它看起来像 3 。即使+1或-1,它也将 100 010

2) What I really cant understand it last 3 bits 011. It looks like 3. Even +1 or -1 it'll be 100 or 010

谢谢

推荐答案

您对这些负数应该是什么样的理解是有缺陷的。 Java对负数使用二进制补码,基本规则是取正数,反转所有位然后加一。这会让你产生负面影响。

Your understanding of what those negative numbers should look like is flawed. Java uses two's complement for negative numbers and the basic rule is to take the positive, invert all bits then add one. That gets you the negative.

因此你知道五,是:

0000...00000101

反转给你:

1111...11111010

然后添加一个给出:

1111...11111011

你为 -5 显示的位模式是什么叫做sign / magnitude,其中你可以简单地通过翻转最左边的位来否定一个数字。这在C实现中被允许作为之一,但Java只使用两个补码(对于它的负整数)。

The bit pattern you have shown for -5 is what's called sign/magnitude, where you negate a number simply by flipping the leftmost bit. That's allowed in C implementations as one of the three possibilities, but Java uses two's complement only (for its negative integers).

这篇关于Java中负整数的二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 18:15