How to tell if hex value is negative?

后端 未结 4 1206
野趣味
野趣味 2020-12-16 17:57

I have just learned how to read hexadecimal values. Until now, I was only reading them as positive numbers. I heard you could also write negative hex values.

My issu

4条回答
  •  隐瞒了意图╮
    2020-12-16 18:49

    The answer here in the forum looks good:

    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.

    and

    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.

提交回复
热议问题