Java 语言中的 long
类型虽然是64位, 但却不是 unsigned
的. 你问我为何, 我也不知道, 不过倒是可以参考几句 Gosling 的采访:
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.
Java 这个设计真的好鸡肋, 但说实话, 写了这么久 Java 真的很少用到 uint64
类型. 不过最近由于使用 protocol buffer 编码数据, 有同事设计了一个编码规则, 就真的遇到了实实在在的 uint64
类型的数据, 在 Go 语言中肯定是没有问题, 可转到 Java 中就变成了负数, 数据需要 JOIN, 因此只有想法子转成字符串. 代码也很简单:
// Guava 中有 UnsignedLong 实现
public String toUint64String(long longValue) {
final String binaryString = Long.toBinaryString(longValue);
final UnsignedLong unsignedLong = UnsignedLong.valueOf(binaryString, 2);
return unsignedLong.toString();
}
谨以此文, 鄙视一下 Java 中鸡肋的设计.
-- EOF --