【问题标题】:Signed and unsigned data types in javajava中的有符号和无符号数据类型
【发布时间】:2014-02-01 02:17:42
【问题描述】:

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

我读过Why doesn't Java support unsigned ints?,但我不明白它非常复杂的解释(至少对我来说)。

【问题讨论】:

  • 它让事情变得简单。
  • @zapl try char ch = '0'; ch *= 1.1; System.out.println(ch); 给你4
  • @zapl 引用authoritative sourceThe numeric types are the integral types and the floating-point types. The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units.
  • @zapl 是的,与byteshort 相同,但本质上它是一个16 位的值,实际上是一个数字。

标签: java types


【解决方案1】:

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

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

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

为了保持一致,它们都像 floatdouble 一样被签名但是有符号字节很少有用,并且考虑到它们允许无符号 16 位 char 具有无符号 byte 可能会做得更多感觉。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • char 未签名。出于同样的原因,字节应该是未签名的恕我直言。例如InputStream.read() 读取一个无符号字节。
    • Joshua Bloch 会说这很奇怪,但在 C/C++ 中,大多数实现都有一个带符号的 8 位 char
    猜你喜欢
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2012-10-27
    • 2020-04-15
    相关资源
    最近更新 更多