📜  Java的.nio.ByteOrder类在Java中

📅  最后修改于: 2022-05-13 01:55:51.442000             🧑  作者: Mango

Java的.nio.ByteOrder类在Java中

ByteOrder 是Java.nio 包中的一个类。一般来说,Byte Order 是指 ByteOrder 的枚举。

  • 在Java有原始数据类型,如int、char、float、double,它们将以一定数量的字节将数据存储在主内存中。
  • 例如,一个字符或一个短整数占用2个字节,一个32位整数或一个浮点值占用4个字节,一个长整数或一个双精度浮点值占用8个字节。
  • 并且这些多字节类型之一的每个值都存储在一系列连续的内存位置中。
  • 这里考虑一个占8个字节的长整数,这8个字节在内存中(从低地址到高地址)可以存储为13、17、21、25、29、34、38、42;这种安排被称为大端顺序(最高有效字节,“大”端,存储在最低地址)。
  • 或者,这些字节可以存储为 42、38、34、29、25、21、17、13;这种安排被称为小端顺序(最低有效字节,“小”端,存储在最低地址到最高地址)。

ByteOrder 类有两个字段

FieldDescription
BIG_ENDIANThis is a field that will be denoting big-endian byte order.
LITTLE_ENDIANThis is a field that will be Constant denoting little-endian byte order.

语法:类声明

public final class ByteOrder extends Object {}

该类的方法如下:



MethodsDescription
nativeOrder()

This method is defined to increase the performance of JVM by allocating direct buffer in the same order to the JVM.

This method returns the native byte order of the hardware upon which this Java virtual machine is running.

toString()This method returns the string which is defined in a specified way.

执行:

例子

Java
// Java Program to demonstrate ByteOrder Class
  
// Importing input output and utility classes
import java.io.*;
  
// Importing required classes from java.nio package
// for network linking
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args) throws Exception
    {
  
        // Here object is created and allocated and
        // it with 8 bytes of memory
        ByteBuffer buf = ByteBuffer.allocate(8);
  
        // This line of code prints the os order
        System.out.println("OS Order         :- "
                           + ByteOrder.nativeOrder());
  
        // This line of code prints the ByteBuffer order
        // Saying that whether it is in BIG_ENDIAN or
        // LITTLE_ENDIAN
        System.out.println("ByteBuffer Order :- "
                           + buf.order());
  
        // Here the conversion of int to byte takes place
        buf.put(new byte[] { 13, 17, 21, 25 });
  
        // Setting the bit set to its complement using
        // flip() method of Java BitSet class
        buf.flip();
  
        IntBuffer integerbuffer = buf.asIntBuffer();
  
        System.out.println("{" + integerbuffer.position()
                           + " : " + integerbuffer.get()
                           + "}");
  
        integerbuffer.flip();
  
        buf.order(ByteOrder.LITTLE_ENDIAN);
  
        integerbuffer = buf.asIntBuffer();
  
        System.out.println("{" + integerbuffer.position()
                           + " : " + integerbuffer.get()
                           + "}");
    }
}


输出
OS Order         :- LITTLE_ENDIAN
ByteBuffer Order :- BIG_ENDIAN
{0 : 219223321}
{0 : 420811021}