为什么0XFF在Java中解释为-1 [英] Why 0XFF is interpreted as -1 in java

查看:105
本文介绍了为什么0XFF在Java中解释为-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



有人可以告诉我为什么Java中将0XFF解释为-1吗?
如何获得255而不是-1的值?

谢谢

Hi,

can anybody plz tell me why 0XFF is interpreted as -1 in java?
What should one do to get 255 value instead of that -1?

Thanks

推荐答案

我假设您正在看到此消息,因为您将0xFF存储在一个字节中,在这种情况下,可以找到答案
I am assuming you are seeing this because you are storing 0xFF in a byte, in which case the answer can be found here[^].


因为解释为有符号整数,并且可以具有-128到127之间的值.无符号整数将表示您想要的值,即255.

祝您好运!
Because it is interpreted as a signed integer and can have values from -128 up to 127. An unsigned integer would represent the value you want, namely 255.

Good luck!


Java使用带符号的整数的二进制补码"表示法,请参见http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html [ ^ ].

这是什么意思?看到这个:
http://en.wikipedia.org/wiki/Signed_number_representations#One.27s_complement [ ^ ],
http://en.wikipedia.org/wiki/Two%27s_complement [
Java uses the "two''s complement" presentation for signed integer, see http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html[^].

What does it mean? See this:
http://en.wikipedia.org/wiki/Signed_number_representations#One.27s_complement[^],
http://en.wikipedia.org/wiki/Two%27s_complement[^].

Just one example of that won''t help you (and may probably greatly confuse). You need to understand the idea, then you can build the examples by yourself.

Many people have naive idea that the negative values are represented with value bits and sign bits, so flipping the sign bit will simply change the sing of the number leaving the absolute value the same. It seems simple, but not convenient at all. First of all, you would have to presentation for the same number: +0 and -0, effectively loosing one bitmap value. Also, the simple CPU algorithms of addition and subtraction would need to examine the sign. In real life, the CPUs arithmetic is designed in much more clever way: the arithmetic operations are carried out without having to examine the sign of operands. You will understand it reading about the signed number presentations in the articles I referenced above and on some simple examples with paper an pencil.

—SA


这篇关于为什么0XFF在Java中解释为-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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