如何判断十六进制值是否为负数?

How to tell if hex value is negative?

我刚刚学会了如何读取十六进制值。直到现在,我只是把它们读作正数。我听说你也可以写负十六进制值。

我的问题是我无法判断一个值是负值还是正值。 我在这里和那里找到了一些解释,但如果我尝试使用在线十六进制到十进制转换器来验证它们,它们总是给我不同的结果。

我找到的来源:

https://coderanch.com/t/246080/java-programmer-OCPJP/certification/Negative-Hexadecimal-number

如果我理解正确,这意味着:
如果一个十六进制值的所有位都大于 7 作为其第一个十六进制数字,则它是负数。
所有'F'开头或第一位的意思是该值为负数,不计算

例如,如果十六进制值以 32 位写入:
FFFFF63C => 负 (-2500 ?)
844fc0bb => 负 (-196099909 ?)
F44fc0bb => 负 (-196099909 ?)
FFFFFFFF => 负 (-1 ?)
7FFFFFFF => 正面

我说的对吗?如果不是,你能告诉我我哪里不对吗?

阅读二进制补码表示:https://en.wikipedia.org/wiki/Two%27s_complement

我认为了解如何处理负数(通常)的最简单方法是写下一个小的二进制数,然后弄清楚如何减一。当你达到 0 并再次应用该方法时 - 你会发现你突然得到全 1。这就是“-1”(通常)的表示方式:二进制中的所有 1 或十六进制中的所有 f。通常,如果您使用带符号的数字,则它们由第一个(最高有效位)位表示。也就是说,如果您使用的位数是四的倍数,那么如果第一个十六进制数字是 8,9,A,B,C,D,E 或 F,则该数为负数。

取反的方法是:

  1. 反转所有位
  2. 加 1

这种表示法(二进制补码)的另一个好处是您只能得到一个表示零的方法,如果您通过设置 MSB 或只是将它们取反来标记有符号数,情况就不会如此。

forum这里的答案看起来不错:

Each hexadecimal "digit" is 4 bits. The d in the high order position is 1101. So you see it's got a high bit of one, therefore the whole number is negative.

A hex number is always positive (unless you specifically put a minus sign in front of it). It might be interpreted as a negative number once you store it in a particular data type. Only then does the most significant bit (MSB) matter, but it's the MSB of the number "as stored in that data type". In that respect the answers above are only partially correct: only in the context of an actual data type (like an int or a long) does the MSB matter.

If you store "0xdcafe" in an int, the representation of it would be "0000 0000 0000 1101 1100 1010 1111 1110" - the MSB is 0. Whereas the representation of "0xdeadcafe" is "1101 1110 1010 1101 1100 1010 1111 1110" - the MSB is 1.

据我了解,你总是需要看最左边的数字来判断标志。如果是十六进制,则 0-7 为正,8-f 为负。或者,您可以将十六进制转换为二进制,如果最左边的数字为 1,则该数字为负数。

十六进制 <-> 二进制 <-> 符号
0-7 <-> 0000-0111 <-> 位置
8-F <-> 1000-1111 <-> 否定

您可以通过检查其最高有效位(最高位)来判断十六进制整数是正数还是负数。如果数字≥8,则为负数;如果数字≤7,则为正数。例如十六进制8A20为负数,7FD9为正数