分享

java byte 与int的互相转换

 cherishchen 2006-08-09
 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;
    }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约