java byte 与int的互相转换

1.byte uses 1 byte while int uses4 bytes.

2. integer literals like "45" are of byte int not byte.
If you want a literal to be a byte, you have to
cast it: "(byte)45".

3. When values are promoted as part of an expression
or as parameters to a method call, they may be
promoted to int, but never to byte.

4. Many parts of the Java language used int, but none
of them use byte. For example, the length of an
array is an int.

/**
     * Convert  an int to a byte array
     *
     * @param value int
     * @return byte[]
     */

public static byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }



    /**
     * Convert the byte array to an int starting from the given offset.
     *
     * @param b The byte array
     * @param offset The array offset,如果byte数组长度就是4,则该值为0
     * @return The integer
     */
    public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值