Java _signed_ 字节原始类型有什么实际用途吗? [英] Are there any real life uses for the Java _signed_ byte primitive type?

查看:26
本文介绍了Java _signed_ 字节原始类型有什么实际用途吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些莫名其妙的原因,byte 原始类型是在 Java 中签名的.这意味着有效值为 -128..127 而不是通常的 0..255 范围,表示一个字节中的 8 个有效位(没有符号位).

For some inexplicable reason the byte primitive type is signed in Java. This mean that valid values are -128..127 instead of the usual 0..255 range representing 8 significant bits in a byte (without a sign bit).

这意味着所有字节操作代码通常都会进行整数计算并最终屏蔽掉最后 8 位.

This mean that all byte manipulation code usually does integer calculations and end up masking out the last 8 bits.

我想知道是否有任何现实生活场景中 Java byte 原始类型非常适合,或者它是否只是一个完全无用的设计决策?

I was wondering if there is any real life scenario where the Java byte primitive type fits perfectly or if it is simply a completely useless design decision?

唯一的实际用例是本机代码的单字节占位符.换句话说,不要在 Java 代码中作为字节进行操作.

The sole actual use case was a single-byte placeholder for native code. In other words, not to be manipulated as a byte inside Java code.

我现在看到一个内部紧密循环需要除以 7(数字 0..32)的地方,因此可以使用字节作为数据类型来完成查找表,因此可以考虑将内存使用量保持在较低水平L1 缓存使用.这不是指有符号/无符号,而是实际使用的情况.

I have now seen a place where an inner tight loop needed to divide by 7 (numbers 0..32) so a lookup table could be done with bytes as the datatype so the memory usage could be kept low thinking of L1 cache usage. This does not refer to the signed/unsignedness but was a case of an actual usage.

推荐答案

Josh Bloch 最近 在一个表示这是语言中的错误之一.

Josh Bloch recently mentioned in a presentation that this is one of the mistakes in the language.

我认为这背后的原因是java没有无符号数字类型,并且byte应该符合该规则.(注:char 是无符号的,但不代表数字)

I think the reason behind this is that java does not have unsigned numeric types, and byte should conform to that rule. (Note: char is unsigned, but does not represent numbers)

至于具体问题:我想不出任何例子.即使有例子,它们也会少于 0..255 的例子,它们可以使用掩码(而不是多数)来实现

As for the particular question: I can't think of any example. And even if there were examples, they would be fewer than the ones for 0..255, and they could be implemented using masking (rather than the majority)

这篇关于Java _signed_ 字节原始类型有什么实际用途吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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