简体   繁体   English

Java中的byte []如何实际存储数据

[英]How does a byte[] in java actually store data

If I have the following: 如果我有以下内容:

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

I know that the size of each element would be one byte. 我知道每个元素的大小将是一个字节。 But what I don't seem to understand is how would the integer 87 be stored in one byte? 但是我似乎不明白,整数87将如何存储在一个字节中? Or, how does the byte[] store data? 或者, byte[]如何存储数据?

EDIT: I see that you can store -128 to 127 in a byte here in java. 编辑:我看到您可以在Java中的一个字节中存储-128到127。 So, does that mean there is no way to store anything greater than or lesser than those numbers in a byte[] ? 那么,这是否意味着没有办法在byte[]存储大于或小于这些数字的任何内容? If so, doesn't that limit the use of this? 如果是这样,这是否限制了此方法的使用? Or am not understanding the exact places to use a byte[] . 还是不了解使用byte[]的确切位置。

A byte is 8 bits. 字节为8位。 2^8 is 256, meaning that 8 bits can store 256 distinct values. 2^8是256,这意味着8位可以存储256个不同的值。 In Java, those values are the numbers in the range -128 to 127, so 87 is a valid byte, as it is in that range. 在Java中,这些值是-128到127之间的数字,因此87是有效字节,因为它在该范围内。

Similarly, try doing something like byte x = 200 , and you will see that you get an error, as 200 is not a valid byte. 类似地,尝试执行类似byte x = 200 ,您会看到错误,因为200 不是有效字节。

A byte is just an 8-bit integer value. 一个byte只是一个8位整数值。 Which means it can hold any value from -2^7 to 2^7-1, which includes all of the number in {87, 79, 87, 46, 46, 46}. 这意味着它可以保存-2 ^ 7到2 ^ 7-1之间的任何值,包括{87,79,87,46,46,46}中的所有数字。

An integer in java, is just a 4-byte integer, allowing it to hold -2^31 to 2^31 - 1 Java中的一个integer ,仅是一个4字节的整数,允许它容纳-2 ^ 31至2 ^ 31-1

A Java byte is a primitive with a minimum value of -128 and a maximum value of 127 (inclusive). Java字节是具有最小值-128和最大值127(含)的原语。 87 is within the allowed range. 87在允许的范围内。 The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. 字节数据类型对于在大数组中节省内存非常有用,因为内存节省实际上很重要。

A byte[] is an Object which stores a number of these primitives. byte []是一个存储许多这些原语的对象。

I think the short answer is that byte[] stores bytes. 我认为简短的答案是byte []存储字节。 The number 87 in your array above it a byte, not an int. 数组上方的数字87是一个字节,而不是int。 If you were to change it to 700 (or anything higher than 127) you'd get a compile error. 如果将其更改为700(或大于127的任何值),则会出现编译错误。 Try it. 试试吧。

You can use byte to store values of 8 bit in it which have a (signed) range from from -128 to 127 . 您可以使用byte在其中存储8位值,其(有符号)范围为-128127

With byte[] you can do some special operations like building String s from a given bytestream and decode them with a desired Charset , and some functions will give you byte[] as their return value. 使用byte[]您可以执行一些特殊操作,例如从给定的字节流中构建String ,并使用所需的Charset对其进行解码,并且某些函数将为您提供byte[]作为其返回值。

I don't know enough about the internals of the JVM but it might save memory though. 我对JVM的内部了解不足,但它可能会节省内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM