Java字节基元类型是否有任何实际用途? [英] Are there any real life uses for the Java byte primitive type?

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

问题描述

出于某种莫名其妙的原因, 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.

推荐答案

令人惊讶的是,我只是用<$上周第一次在Java中使用c $ c> byte ,所以我确实有一个(尽管是不寻常的)用例。我正在编写一个本机Java函数,它允许您在可以调用的库中实现一个函数通过Java。需要将Java类型转换为本机语言中的类型,在本例中为C

Amazingly, I just used byte in Java for the first time last week, so I do have an (albeit unusual) use-case. I was writing a native Java function, which lets you implement a function in a library that can be called by Java. Java types need to be converted to types in the native language, in this case C

获取字节数组所需的函数,但是(忘记了 byte 当时完全输入)我需要一个 char [] 。为C函数生成的签名Java将该参数的类型赋予 jcharArray ,它可以转换为一堆 jchar s,在 jni.h 中的类型定义为 unsigned short 。当然,这不是相同的大小 - 它是2个字节而不是1.这导致了底层代码的各种问题。使Java类型 byte [] 产生 jbyteArray ,并且 jbyte 是typedef-ed到 signed char ,这是正确的大小

The function needed to take an array of bytes, but (forgetting about the byte type entirely at the time) I had it take a char[]. The signature Java generates for the C function gives the type of that parameter as jcharArray, which can be converted to a bunch of jchars, which are typedef-ed in jni.h to unsigned short. Naturally, that is not the same size -- it's 2 bytes instead of 1. This caused all sorts of problems with the underlying code. Making the Java type byte[] resulted in a jbyteArray, and jbyte on Linux is typedef-ed to signed char, which is the right size

这篇关于Java字节基元类型是否有任何实际用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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