java Java中字节类型的用途

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16194681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:10:57  来源:igfitidea点击:

Purpose of byte type in Java

javabyteprimitive

提问by H?i Phong

I read this line in the Java tutorial:

我在 Java 教程中阅读了这一行:

byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

byte:字节数据类型是一个 8 位有符号二进制补码整数。它的最小值为 -128,最大值为 127(含)。字节数据类型可用于在大型数组中节省内存,其中内存节省实际上很重要。它们也可以代替 int 使用它们的限制有助于澄清您的代码;变量范围有限的事实可以作为一种文档形式。

I don't clearly understand the bold line. Can somebody explain it for me?

我不太清楚粗线。有人可以为我解释一下吗?

采纳答案by Mr. Adobo

Byte has a (signed) range from -128 to 127, where as int has a (also signed) range of ?2,147,483,648 to 2,147,483,647.

Byte 的(有符号)范围从 -128 到 127,而 int 的(也有符号)范围是 ?2,147,483,648 到 2,147,483,647。

What it means is that since the values you're going to use will always be between that range, by using the byte type you're telling anyone reading your code this value will be at most between -128 to 127 always without having to document about it.

这意味着,由于您要使用的值将始终在该范围之间,因此通过使用字节类型,您可以告诉任何阅读您的代码的人,该值最多始终在 -128 到 127 之间,而无需记录关于它。

Still, proper documentation is always key and you should only use it in the case specified for readability purposes, not as a replacement for documentation.

尽管如此,正确的文档始终是关键,您应该只在出于可读性目的而指定的情况下使用它,而不是作为文档的替代品。

回答by alexclooze

If you're using a variable which maximum value is 127 you can use byteinstead of intso others know without reading any ifconditions after, which may check the boundaries, that this variable can only have a value between -128 and 127.

如果您使用的是最大值为 127 的变量,您可以使用byte而不是int让其他人知道之后无需阅读任何if条件,这可能会检查边界,该变量只能具有 -128 和 127 之间的值。

So it's kind of self-documenting code - as mentioned in the text you're citing.

所以它是一种自我记录的代码 - 正如你在引用的文本中提到的那样。

Personally, I do not recommend this kind of "documentation" - only because a variable can only hold a maximum value of 127 doesn't reveal it's really purpose.

就我个人而言,我不推荐这种“文档”——只是因为一个变量只能容纳 127 的最大值并不能揭示它的真正用途。

回答by Bernhard Barker

I imagine one can use bytefor anything dealing with actualbytes.

我想可以byte用于处理实际字节的任何内容。

Also, the parts (red, green and blue) of colors commonly have a range of 0-255 (although byteis technically -128 to 127, but that's the same amount of numbers).

此外,颜色的部分(红色、绿色和蓝色)通常在 0-255 的范围内(虽然byte技术上是 -128 到 127,但这是相同数量的数字)。

There may also be other uses.

也可能有其他用途。

The general opposition I have to using byte(and probably why it isn't seen as often as it can be) is that there's lots of casting needed. For example, whenever you do arithmetic operations on a byte(except X=), it is automatically promoted to int(even byte+byte), so you have to cast it if you want to put it back into a byte.

我必须使用的普遍反对意见byte(可能也是为什么它没有尽可能频繁地出现)是需要大量的演员表。例如,每当您对byte(except X=)进行算术运算时,它都会自动提升为int(even byte+byte),因此如果要将其放回byte.

A very elementary example:

一个非常基本的例子:

FileInputStream::readreturns a bytewrapped in an int(or -1). This can be cast to an byteto make it clearer. I'm not supporting this example as such(because I don't really (at this moment) see the point of doing the below), just saying something similar may make sense.

FileInputStream::read返回一个byte包裹在一个int(或 -1)中的。这可以转换为 anbyte以使其更清楚。我不支持这个例子(因为我真的(此时)没有看到做下面的点),只是说一些类似的事情可能是有道理的。

It could also have returneda byte in the first place (and possibly thrown an exception if end-of-file). This may have been even clearer, but the way it was done does make sense.

它也可能首先返回一个字节(并且可能在文件结束时抛出异常)。这可能更清楚,但这样做的方式确实有意义。

FileInputStream file = new FileInputStream("Somefile.txt");
int val;
while ((val = file.read()) != -1)
{
  byte b = (byte)val;
  // ...
}

If you don't know much about FileInputStream, you may not know what readreturns, so you see an intand you may assume the valid range is the entire range of int(-2^31 to 2^31-1), or possibly the range of a char(0-65535) (not a bad assumption for file operations), but then you see the cast to byteand you give that a second thought.

如果您不太了解FileInputStream,您可能不知道read返回什么,因此您会看到int并且您可能会假设有效范围是int(-2^31 到 2^31-1)的整个范围,或者可能是a char(0-65535)(对于文件操作来说,这是一个不错的假设),但是随后您看到了强制转换byte,然后您再考虑一下。

If the return type were to have been byte, you would know the valid range from the start.

如果返回类型是byte,您将从一开始就知道有效范围。

Another example:

另一个例子:

One of Color's constructors could have been changed from 3 int's to 3 byte's instead, since their range is limited to 0-255.

其中一个颜色的构造可能是从3改为int's到3byte的替代,因为它们的范围被限制在0-255。

回答by Bucket

Integersin Java are stored in 32 bits; bytesare stored in 8 bits.

Integers在 Java 中以 32 位存储;bytes以 8 位存储。

Let's say you have an array with one million entries. Yikes! That's huge!

假设您有一个包含一百万个条目的数组。哎呀!那是巨大的!

int[] foo = new int[1000000];

Now, for each of these integers in foo, you use 32 bitsor 4 bytesof memory. In total, that's 4 million bytes, or 4MB.

现在,对于 中的每个整数foo,您使用32 位4 个字节的内存。总共有400 万字节,即4MB

Remember that an integerin Java is a whole number between -2,147,483,648 and 2,147,483,647 inclusively. What if your array fooonly needs to contain whole numbers between, say, 1 and 100? That's a whole lot of numbers you aren't using, by declaring fooas an intarray.

请记住,integerJava 中的an是介于 -2,147,483,648 和 2,147,483,647 之间的整数。如果您的数组foo只需要包含介于 1 和 100 之间的整数怎么办?通过声明fooint数组,您没有使用大量数字。

This is when bytebecomes helpful. Bytesstore whole numbers between -128 and 127 inclusively, which is perfect for what you need! But why choose bytes? Because they use one-fourth of the space of integers. Now your array is wasting less memory:

这就是byte有用的时候。Bytes存储 -128 和 127 之间的整数,非常适合您的需要!但为什么选择bytes因为它们使用了整数空间的四分之一。现在您的阵列浪费的内存更少:

byte[] foo = new byte[1000000];

Now each entry in footakes up 8 bitsor 1 byteof memory, so in total, footakes up only 1 million bytesor 1MBof memory.

现在每个条目都foo占用8位1个字节的内存,所以总共foo只占用100万个字节1MB的内存。

That's a hugeimprovement over using int[]- you just saved 3MB of memory.

与使用相比,这是一个巨大的改进int[]- 您只节省了 3MB 的内存。

Clearly, you wouldn't want to use this for arrays that hold numbers that would exceed 127, so another way of reading the bold line you mentioned is, Since bytes are limited in range, this lets developers know that the variable is strictly limited to these bounds. There is no reason for a developer to assume that a number stored as a byte would ever exceed 127 or be less than -128. Using appropriate data types saves space and informs other developers of the limitations imposed on the variable.

显然,您不想将其用于包含超过 127 的数字的数组,因此读取您提到的粗线的另一种方法是,由于字节范围有限,这让开发人员知道该变量严格限于这些界限。开发人员没有理由假设存储为字节的数字会超过 127 或小于 -128。使用适当的数据类型可以节省空间并告知其他开发人员对变量施加的限制。

回答by Máté Gelei

It means that knowing that a value is explicitly declared as a very small number might help you recall the purpose of it.

这意味着知道一个值被明确声明为一个非常小的数字可能会帮助您回忆起它的用途。

Go for real docs when you have to create a documentation for your code, though, relying on datatypes is not documentation.

当您必须为代码创建文档时,请寻找真正的文档,但是,依赖数据类型不是文档。

回答by usumoio

An int covers the values from 0 to 4294967295 or 2 to the 32nd power. This is a huge range and if you are scoring a test that is out of 100 then you are wasting that extra spacce if all of your numbers are between 0 and 100. It just takes more memory and harddisk space to store ints, and in serious data driven applications this translates to money wasted if you are not using the extra range that ints provide.

int 涵盖从 0 到 4294967295 或 2 到 32 次方的值。这是一个很大的范围,如果你的测试得分超过 100,那么如果你的所有数字都在 0 到 100 之间,那么你就是在浪费额外的空间。它只是需要更多的内存和硬盘空间来存储整数,严重的是如果您不使用 ints 提供的额外范围,这将转化为数据驱动的应用程序浪费金钱。

回答by Nishant sharma

byte data types are generally used when you want to handle data in the forms of streams either from file or from network. Reason behind this is because network and files works on the concept of byte.

当您希望以流的形式处理来自文件或网络的数据时,通常会使用字节数据类型。这背后的原因是因为网络和文件基于字节的概念。

Example: FileOutStream always takes byte array as input parameter.

示例: FileOutStream 始终将字节数组作为输入参数。