整型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<String>) {
    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 (index<source.size){
        target+=(source[index].toInt() and 0xff).shl(8*index)
        index++
    }
    return target
}
运行结果:
212123
-101 60 3 0 
212123

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值