Java Endian conversion (based on the ByteBuffer)

The size of the end of the basics:

Small end (little-endian): low byte first, high byte. Big-endian (Big-Endian), and vice versa. Specifically, it is to make it clear that the storage order CPU architecture 1 word (word) in a byte. Computer memory data is the natural order: the low first-come, after the high

All JAVA binaries are by big-endian storage , this storage method is also known as Network the Order. That is, on all platforms, such as Mac, PC, UNIX, etc. run JAVA, do not consider the issue of the size of the terminal. The trouble is developed in different languages programs exchange data, such as I recently project, binary file generated by the C, to Json format sent, through redis message channel, the C language is little endian by default. Some platforms (such as Mac, IBM 390) with built-in big-endian mode, some little-endian mode with built-in platform (such as Intel). JAVA help you shield the differences of each platform byte order . Much so

For example, 32-bit hexadecimal 0x45679812 is stored in memory as follows:

 

Based on the ByteBuffer (Order can be set by the big end or the small end, the large end defaults -  Big-Endian ), code implementation below (--2 support network port byte conversion and a 4-byte int):

    /**
     * The small end big endian data bytes into the data
     * <p>
     * Big-endian byte default network transmission, java all of the big end (platform independent)
     * About "Little-Endian and Big-Endian", please refer to:
     *
     * @param bytes
     * @Return integer obtained after transformation
     * @Link https://howtodoinjava.com/java/basics/little-endian-and-big-endian-in-java/
     * </p>
     */
    private int bytesToBigEndian(byte[] bytes) {
        int result = 0;
        if (bytes == null || bytes.length < 0)
            return -1;

        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.BIG_ENDIAN);
        if (bytes.length == RECORD_BYTES_SIZE) {
            result = buffer.getInt();
        } else if (bytes.length == PORT_BYTES_SIZE) {
            // 端口号:0 ~ 65535; Short: -32768 ~ 32767
            short tmp = buffer.getShort();
            result = tmp < 0 ? getUnsignedShort(tmp) : tmp;
        }
        if (result < 0) {
            logger.info("Length = " + result + " ; original data:" + bytes);
        }
        return result;
    }

 

附:

1)https://howtodoinjava.com/java/basics/little-endian-and-big-endian-in-java/

 

*****************************************************************************************************

精力有限,想法太多,专注做好一件事就行

  • 我只是一个程序猿。5年内把代码写好,技术博客字字推敲,坚持零拷贝和原创
  • 写博客的意义在于打磨文笔,训练逻辑条理性,加深对知识的系统性理解;如果恰好又对别人有点帮助,那真是一件令人开心的事

*****************************************************************************************************

Guess you like

Origin www.cnblogs.com/NaughtyCat/p/little-endian-and-big-endian-based-on-bytebuffer-in-java.html