java中的有符号和无符号数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21089540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:29:48  来源:igfitidea点击:

Signed and unsigned data types in java

javatypes

提问by ReflectionHack

I have a bit of confusion regarding which unsigned data types does Java support?

我对 Java 支持哪些无符号数据类型有些困惑?

I have read thisbut I don't understand its very complicated explanation (to me at least).

我读过这个,但我不明白它非常复杂的解释(至少对我来说)。

采纳答案by Peter Lawrey

Java only supports signed types (except char) because it was assumed that one type was simpler for beginners to understand than having two types for each size. In C it was perceived to be a source of error so support for unsigned types was not included.

Java 只支持有符号类型(除了char),因为它假定一种类型比每种大小有两种类型更容易让初学者理解。在 C 中,它被认为是错误的来源,因此不包括对无符号类型的支持。

So the designers picked four sizes

所以设计师选择了四种尺寸

  • byte, 8 bit
  • short, 16 bit
  • int, 32 bit
  • long, 64 bit.
  • byte, 8 位
  • short, 16 位
  • int, 32 位
  • long, 64 位。

and to keep things consistent they were all signed just like floatand doubleHowever a signed byte is rarely very useful and given they allowed unsigned 16-bit charhaving an unsigned bytemight have made more sense.

并且为了保持一致,它们都像float和一样double有符号,但是有符号字节很少很有用,并且考虑到它们允许无符号的 16 位char具有无符号byte可能更有意义。

Where this doesn't work so well is when you have to interact with systems which use unsigned integer types. This can be source of confusion and to which type to use instead because often it doesn't make any difference. Java 8 will have operations to support unsigned types as well. These are added to the wrapper classes like Integerand Long

当您必须与使用无符号整数类型的系统进行交互时,这不起作用。这可能会导致混淆以及使用哪种类型,因为它通常没有任何区别。Java 8 也将具有支持无符号类型的操作。这些被添加到包装类中,如IntegerLong

回答by Evgeniy Dorofeev

All Java numeric types are signed. This was the designers decision. Some people think it was a bad idea to have signed byte. J.Bloch in an interview said "I'm going to say that the strangest thing about the Java platform is that the byte type is signed." http://www.theserverside.com/news/thread.tss?thread_id=51624

所有 Java 数字类型都是有符号的。这是设计师的决定。有些人认为对字节进行签名是个坏主意。J.Bloch 在接受采访时说:“我要说 Java 平台最奇怪的地方是字节类型是有符号的。” http://www.theserverside.com/news/thread.tss?thread_id=51624