Bytes数组处理工具

记一个byte数组与int互转、与string互转、字节替换的例子,与int互转的代码解析回头再补上

/**
 * Bytes数组处理工具
 * @author
 */
public class ByteUtils {

    /**
     * byte转int
     * @param b
     * @param start
     * @param len
     * @return
     */
    public static int bytes2Int(byte[] b, int start, int len) {
        int sum = 0;
        int end = start + len;
        for (int i = start; i < end; i++) {
            //在byte转int时,需要保持二进制补码的一致性,所以要& 0xff。见博客下源码分析:
            int n = ((int) b[i]) & 0xff;
            n <<= (--len) * 8;
            sum = n + sum;
        }
        return sum;
    }

    /**
     * int转byte
     * @param value
     * @param len
     * @return
     */
    public static byte[] int2Bytes(int value, int len) {
        byte[] b = new byte[len];
        for (int i = 0; i < len; i++) {
            b[len - i - 1] = (byte) ((value >> 8 * i) & 0xff);
        }
        return b;
    }

    /**
     * byte转string
     * @param b
     * @param start
     * @param len
     * @return
     */
    public static String bytes2String(byte[] b, int start, int len) {
        return new String(b, start, len);
    }

    /**
     * String转byte
     * @param str
     * @return
     */
    public static byte[] string2Bytes(String str) {
        return str.getBytes();
    }

    /**
     * 字节替换
     * @param originalBytes
     * @param offset
     * @param len
     * @param replaceBytes
     * @return
     */
    public static byte[] bytesReplace(byte[] originalBytes, int offset, int len, byte[] replaceBytes) {
        byte[] newBytes = new byte[originalBytes.length + (replaceBytes.length - len)];
        System.arraycopy(originalBytes, 0, newBytes, 0, offset);
        System.arraycopy(replaceBytes, 0, newBytes, offset, replaceBytes.length);
        System.arraycopy(originalBytes, offset + len, newBytes, offset + replaceBytes.length, originalBytes.length - offset - len);
        return newBytes;
    }
}

一、& 0xff的作用
举个简单的例子:
byte[] b = new byte[5];
b[0] = -12;
byte 8位二进制 = 1个字节 char 2个字节 short (2个字节) int(4个字节) long(8个字节) float (4个字节) double(8个字节)
计算机存储数据机制:正数存储的二进制原码,负数存储的是二进制的补码。 补码是负数的绝对值反码加1。
比如-12,-12 的绝对值原码是:0000 1100 取反: 1111 0011 加1: 1111 0100
byte –> int 就是由8位变 32 位 高24位全部补1: 1111 1111 1111 1111 1111 1111 1111 0100 ;
0xFF 是计算机十六进制的表示: 0x就是代表十六进制,A B C D E F 分别代表10 11 12 13 14 15 F就是15 一个F 代表4位二进制:可以看做 是 8 4 2 1。
0xFF的二进制表示就是:1111 1111。 高24位补0:0000 0000 0000 0000 0000 0000 1111 1111;
-12的补码与0xFF 进行与(&)操作 最后就是0000 0000 0000 0000 0000 0000 1111 0100
转换为十进制就是 244。
byte类型的数字要&0xff再赋值给int类型,其本质原因就是想保持二进制补码的一致性。
当byte要转化为int的时候,高的24位必然会补1,这样,其二进制补码其实已经不一致了,&0xff可以将高的24位置为0,低8位保持原样。这样做的目的就是为了保证二进制数据的一致性。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值