整型int和字节数组byte相互转换

Java中整型int和字节数组byte相互转换,在网络编程中这个算法是最基本的算法,我们都知道,在socket传输中,发送、者接收的数据都是 byte数组,但是int类型是4个byte组成的,如何把一个整形int转换成byte数组,同时如何把一个长度为4的byte数组转换为int类型,分别上传Java版本代码和kotlin版本代码(刚学的,试试手,代码运行结果经过校验无误)

Java版本

/**
 * Created by tao.liu on 2017/6/20 0020.
 * 整型int和字节数组byte相互转换
 */
public class Test {
    public static void main(String[] args) {
        int data = 212123;
        System.out.println(data);
        byte[] toByteArray = toByteArray(data, 4);
        for (int i = 0; i < toByteArray.length; i++) {
            System.out.println("["+i+"] = "+toByteArray[i]);
        }
        int i = toInt(toByteArray);
        System.out.println(i);
    }
    /**
     * int数据转数组byte
     *
     * @param source
     * @param len
     * @return
     */
    public static byte[] toByteArray(int source, int len) {
        byte[] target = new byte[len];
        for (int i = 0; i < 4 && i < len; i++) {
            target[i] = (byte) (source >> 8 * i & 0xff);
        }
        return target;
    }
    /**
     * 数组byteint数据
     * @param source
     * @return
     */
    public static int toInt(byte[] source) {
        int target = 0;
        for (int i = 0; i < source.length; i++) {
            target += (source[i] & 0xff) << 8 * i;
        }
        return target;
    }
}
运行结果:
 
  
212123
[0] = -101
[1] = 60
[2] = 3
[3] = 0
212123
 
  
kotlin版本
 
  
 
  
import kotlin.experimental.and

/**
 * Created by tao.liu on 2017/6/20 0020.
 * 整型int和字节数组byte相互转换
 */

fun main(args: Array) {
    var data = 212123
    println(data)
    val toByteArray = toByteArray(data, 4)
    for (b in toByteArray.indices){
        print("${toByteArray[b]} ")
    }
    println()

    val toInt = toInt(toByteArray)
    println(toInt)
}

/**
 * int数据转数组byte
 */
fun toByteArray(source: Int, len: Int): ByteArray {
    var target = byteArrayOf(0,0,0,0)
    var index = 0
    while ((index < 4) && (index < len)) {
        target[index] = (source.shr(8*index)and 0xff).toByte()
        index++
    }
    return target
}

/**
 * 数组byteint数据
 */
fun toInt(source: ByteArray):Int{
    var target = 0
    var index = 0
    while (indexsize){
        target+=(source[index].toInt() and 0xff).shl(8*index)
        index++
    }
    return target
}
运行结果:
212123
-101 60 3 0 
212123

你可能感兴趣的:(Java,kotlin)