java int和byte数组的互相转换(两种方法)

最近在用java调dll的过程中对byte数组和int的相互转化比较频繁,特在此记录。Code Bank

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class Test02 {
    
    //方法一
    
    //int 转化为字节数组
    public static byte[] intTobyte(int num)
    {
        return new byte[] {(byte)((num>>24)&0xff),(byte)((num>>16)&0xff),(byte)((num>>8)&0xff),(byte)(num&0xff)};
    }
    //字节数组转化为int
    public static int byteArrayToInt(byte[] arr)
    {
        return (arr[0]&0xff)<<24|(arr[1]&0xff)<<16|(arr[2]&0xff)<<8|(arr[3]&0xff);
    }
    
    //方法二
    
    //int 转化为字节数组
    public static byte[] intTobyte2(int num)
    {
        byte[] result=null;
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        DataOutputStream dos=new DataOutputStream(bos);
        try {
            dos.writeInt(num);
            result=bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    //字节数组转化为int
    public static int byteArrayToInt2(byte[] arr)
    {
        int result=0;
        ByteArrayInputStream bis=new ByteArrayInputStream(arr);
        DataInputStream dis=new DataInputStream(bis);
        try {
            result= dis.readInt();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    
    public static void main(String[] args) {
        
        int a=-64;
        System.out.println(Arrays.toString(intTobyte(a)));
        System.out.println(byteArrayToInt(intTobyte(a)));
        
        System.out.println(Arrays.toString(intTobyte2(a)));
        System.out.println(byteArrayToInt2(intTobyte2(a)));
        

    }

}

运行结果:


java int和byte数组的互相转换(两种方法)_第1张图片
运行结果

你可能感兴趣的:(java int和byte数组的互相转换(两种方法))