java int和byte数组byte[]互转(超过5字节就有问

2021-04-15  本文已影响0人  Anivia_Hanger
高字节在前,取低4位(int2Bytes(318)= [0x01 0x3E]):
 public static byte[] int2Bytes(int num){ 
        byte[] bytes = new byte[2];//取低4位
        bytes[0] = (byte)(num>>>8);
        bytes[1] = (byte)num;
        return bytes;
    }


高字节在前,取低x位(int2Bytes(318,4)= [0x01 0x3E]):
 public static byte[] int2Bytes(int num, int pcs) {
        byte[] bytes = new byte[pcs / 2];
        int a = 0;
        for (int i = bytes.length - 1; i >= 0; i--) {
            bytes[i]=(byte) (num >>> (a*8));
            a++;
        }
        return bytes;
    }
低字节在前 int2Bytes( 23552,8) = [0x00 0x5C 0x00 0x00]
public static byte[] int2Bytes(int num, int pcs) {
        byte[] bytes = new byte[pcs / 2];
        int a = 0;
        for (int i = 0; i < bytes.length; i++) {
            bytes[i]=(byte) (num >>> (a*8));
            a++;
        }
        return bytes;
    }
byte[]转int
     //低字节在前的byte[]转int    [0x00 0x5C 0x00 0x00] = 23552
 public static int bytes2Int(byte[] bytes) {
        int sum = 0;
        for (int i =  bytes.length-1; i >=0; i--) {
            int n = bytes[i] & 0xff;
            n <<= i * 8;
            sum += n;
        }
        return sum;
    }

     //高字节在前的byte[]转int   [0x00 0x00 0x5C 0x00] = 23552
 public static int bytes2Int(byte[] bytes) {
        int sum = 0;
        int len = bytes.length;
        for (int i = 0; i < bytes.length; i++) {
            int n = bytes[i] & 0xff;
            n <<= (--len) * 8;
            sum += n;
        }
        return sum;
    }
上一篇下一篇

猜你喜欢

热点阅读