Home > Java > javaTutorial > Example analysis of Java byte array manipulation code

Example analysis of Java byte array manipulation code

coldplay.xixi
Release: 2020-07-22 16:09:47
forward
2438 people have browsed it

Example analysis of Java byte array manipulation code

The key to a byte array is that it provides indexed (fast), precise raw access to each 8-bit value stored in that portion of memory, and you can manipulate those bytes Make operations to control each bit. The downside is that the computer just sees each entry as a separate 8-bit number - this might be what your program is dealing with, or you might prefer some more powerful data type like a string that keeps track of its own length and grows as needed , or a float that lets you store say 3.14 regardless of bitwise representation. As a data type, inserting or removing data near the beginning of a long array is inefficient because all subsequent elements need to be shuffled to fill or fill the created/required gaps.

java officially provides a method to operate byte arrays - memory stream (byte array stream) ByteArrayInputStream, ByteArrayOutputStream

ByteArrayOutputStream - byte array merger

/**
  * 将所有的字节数组全部写入内存中,之后将其转化为字节数组
  */
  public static void main(String[] args) throws IOException {
    String str1 = "132";
    String str2 = "asd";
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    os.write(str1.getBytes());
    os.write(str2.getBytes());
    byte[] byteArray = os.toByteArray();
    System.out.println(new String(byteArray));
  }
Copy after login

ByteArrayInputStream——byte array interception

/**
  *  从内存中读取字节数组
  */
  public static void main(String[] args) throws IOException {
    String str1 = "132asd";
    byte[] b = new byte[3];
    ByteArrayInputStream in = new ByteArrayInputStream(str1.getBytes());
    in.read(b);
    System.out.println(new String(b));
    in.read(b);
    System.out.println(new String(b));
  }
Copy after login

Related learning recommendations: Java video tutorial

The above is the detailed content of Example analysis of Java byte array manipulation code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template