java 基本类型与字节数组的互相转换

下面是int 类型跟byte[] 类型的相互转换

        //int 类型转 字节数组(bytes)
public static byte[] intToBytes(int id){
byte[] bytes = new byte[4];
for (int j = 0; j < bytes.length; j++) {
bytes[j]  = (byte)((int)(id >> j*8)& 0xff);
}
return bytes;

}

//字节数组转int 类型
public static int bytesToInt(byte[] bytes){
int result = 0 ;
for (int i = 0; i < bytes.length; i++) {
result = result + (int)((bytes[i] & 0xff) << i*8);
}

return result;
}


public static void main(String[] args) {

    byte[] by = intToBytes(500);
System.out.print("500转字节数组后== ");
for (int i = 0; i < by.length; i++) {
System.out.print(by[i]+",");

}

        System.out.println();
System.out.println("by字节数组转int型后== " + bytesToInt(by));

        }

输出结果:

500转字节数组后== -12,1,0,0,

by字节数组转int型后== 500

如果是转其他数据类型的话 只要把强制转换为int 改为强制转换你需要转换的基本数据类型即可,如:转long类型

//字节数组转long 类型
public static long bytesToInt(byte[] bytes){
long result = 0 ;
for (int i = 0; i < bytes.length; i++) {
result = result + (long )((bytes[i] & 0xff) << i*8);
}

return result;

}


猜你喜欢

转载自blog.csdn.net/qq_40207976/article/details/80265868