Java 语言没有 unsigned 类型

目录 技术

跟 C 语言不同,Java 中没有 unsigned 类型,这点可能让很多人都有过困扰。

那如果碰到确实需要用到 unsigned 类型的情况怎么办呢? 通常的办法就是用更大一号的类型来处理,比如:

  • 处理 unsigned byte,就用 int;
  • 处理 unsigned int,就用 long;
  • 处理 unsigned long,这个不好办,只能用 BigInteger 了。但是要注意的是,Java 中的 long 是 8 bytes,而 C 语言只有4 bytes,所以碰到这种情况的话,那就等同于上面 unsigned int 的情况了。

另外,Java 中比 C 语言增加了一种不带符号的移位操作: >>> ,固定的用 0 来填充左边高位的空缺,这在一定程度上减轻了没有 unsigned 类型带来的影响。

扩展阅读:这里有篇文章介绍了 Java 中怎么处理 unsigned 类型的。文中提到的一篇对 C /C++/Java 语言创始人的访谈中提到了 Java 中没有定义 unsigned 类型的原因,见最后 Gosling 的部分:

Q: Programmers often talk about the advantages and disadvantages of programming
in a "simple language."  What does that phrase mean to you, and is [C/C++/Java] a
simple language in your view?

Ritchie: C (and the others for that matter) are simple in some ways, though they are
also subtle; other, somewhat similar languages like Pascal are arguably simpler. What
has become clear is that aspects of the environment like libraries that aren't part of
the core language are much bigger and more complicated. The 1999 C standard grew
hugely more in the library part than in the language; the C++ STL and other things
are big; AWT and other things associated with Java are too.

Stroustrup: I see three obvious notions of "simple:" to be easy to learn, to make it
easy to express ideas, and to have a one-to-one correspondence to some form of
math. In those terms, none of the three languages is simple. However, once mastered,
C and C++ make it easy to express quite complex and advanced ideas -- especially
when those ideas have to be expressed under real-world resource constraints.

Gosling: For me as a language designer, which I don't really count myself as these days,
what "simple" really ended up meaning was could I expect J. Random Developer to
hold the spec in his head. That definition says that, for instance, Java isn't -- and
in fact a lot of these languages end up with a lot of corner cases, things that nobody
really understands. Quiz any C developer about unsigned, and pretty soon you discover
that almost no C developers actually understand what goes on with unsigned,
what unsigned arithmetic is. Things like that made C complex.
The language part of Java is, I think, pretty simple. The libraries you have to look up.



电子邮件地址不会被公开。 必填项已用*标注