Java代码如何将byte[]和int互相转换呢?

乔欣 Java经验 发布时间:2023-02-01 11:31:30 阅读数:12178 1
下文笔者讲述字节数组和int之间互相转换的方法分享,如下所示
实现思路:
   int转byte[]
    
	int num = 1;
    // int need 4 bytes, default ByteOrder.BIG_ENDIAN
     byte[] result =  ByteBuffer.allocate(4).putInt(number).array();

   byte[]转int
    byte[] byteArray = new byte[] {00, 00, 00, 01};
    int num = ByteBuffer.wrap(bytes).getInt();
例:
int转byte []
 
package com.java265.nio;
import java.nio.ByteBuffer; 
public class IntToByteArrayExample {
 
    public static void main(String[] args) {
 
        int num = 1;
        byte[] result = convertIntToByteArray(num);
 
        System.out.println("Input            : " + num);
        System.out.println("Byte Array (Hex) : " + convertBytesToHex(result));
 
    }
 
    // method 1, int need 4 bytes, default ByteOrder.BIG_ENDIAN
    public static byte[] convertIntToByteArray(int value) {
        return  ByteBuffer.allocate(4).putInt(value).array();
    }
 
    // method 2, bitwise right shift
    public static byte[] convertIntToByteArray2(int value) {
        return new byte[] {
                (byte)(value >> 24),
                (byte)(value >> 16),
                (byte)(value >> 8),
                (byte)value };
    }
 
    public static String convertBytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte temp : bytes) {
            result.append(String.format("%02x", temp));
        }
        return result.toString();
    }
}

byte []转换int

package com.java265.nio;
 
import java.nio.ByteBuffer;
 
public class ByteArrayToIntExample {
 
    public static void main(String[] args) {
 
        // byte = -128 to 127
        byte[] byteArray = new byte[] {00, 00, 00, 01};
 
        int result = convertByteArrayToInt2(byteArray);
 
        System.out.println("Byte Array (Hex) : " + convertBytesToHex(byteArray));
        System.out.println("Result           : " + result);
 
    }
 
    // method 1
    public static int convertByteArrayToInt(byte[] bytes) {
        return ByteBuffer.wrap(bytes).getInt();
    }
 
    // method 2, bitwise again, 0xff for sign extension
    public static int convertByteArrayToInt2(byte[] bytes) {
        return ((bytes[0] & 0xFF) << 24) |
                ((bytes[1] & 0xFF) << 16) |
                ((bytes[2] & 0xFF) << 8) |
                ((bytes[3] & 0xFF) << 0);
    }
 
    public static String convertBytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte temp : bytes) {
            result.append(String.format("%02x", temp));
        }
        return result.toString();
    }
 
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202302/16752223405609.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者