What is Java Byte Array and How should it be used?

后端 未结 1 1370
余生分开走
余生分开走 2021-01-17 07:15

What does it mean by byte array ? I mean it holds the 0s and 1s just like how data is hold in memory ?

For example

String a = \"32\";
byte [] arr =         


        
相关标签:
1条回答
  • 2021-01-17 07:37

    By byte array, it literally means an array where each item is of the byte primitive data type. If you do not know the difference between a byte and a common int (Integer), the main difference is the bit width: bytes are 8-bit and integers are 32-bit. You can read up on that here.

    If you do not know what an array is, an array is basically a sequence of items (in your case a sequence of bytes, declared as byte[]).

    The function a.getBytes() takes a, which is a String, and returns an array of bytes. This can be done because the human-readable characters in a String can be represented as 8-bit numbers, where the mapping between number and character is determined by the CharSet. Examples of two common CharSets are ASCII and UTF-8. Now, arr is an array of bytes, where each byte in the array represents each character in the original string a. In both ASCII and UTF-8, the String "32" is represented by the bytes 51 and 50 in decimal, and 0x33 and 0x32 in hexadecimal.

    Byte arrays are commonly used in applications that read and write data byte-wise, such as socket connections that send data in byte streams through TCP or UDP protocols.

    Hope I could help!

    0 讨论(0)
提交回复
热议问题