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

高字节在前,取低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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容