java byte 与int的互相转换

来源:互联网 发布:淘宝店家等级怎么看 编辑:程序博客网 时间:2024/05/21 13:03
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;
    }
原创粉丝点击