Java 中 byte、byte 數組和 int、long 之間的轉換

Java 中 byte 和 int 之間的轉換源碼:

//byte 與 int 的相互轉換
    public static byte intToByte(int x) {
        return (byte) x;
    }

    public static int byteToInt(byte b) {
        //Java 總是把 byte 當做有符處理;我們可以通過將其和 0xFF 進行二進制與得到它的無符值
        return b & 0xFF;
    }

Java 中 byte 數組和 int 之間的轉換源碼:

/byte 數組與 int 的相互轉換
    public static int byteArrayToInt(byte[] b) {
        return   b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

    public static byte[] intToByteArray(int a) {
        return new byte[] {
            (byte) ((a >> 24) & 0xFF),
            (byte) ((a >> 16) & 0xFF),   
            (byte) ((a >> 8) & 0xFF),   
            (byte) (a & 0xFF)
        };

Java 中 byte 數組和 long 之間的轉換源碼:

private static ByteBuffer buffer = ByteBuffer.allocate(8); 
    //byte 數組與 long 的相互轉換
    public static byte[] longToBytes(long x) {
        buffer.putLong(0, x);
        return buffer.array();
    }

    public static long bytesToLong(byte[] bytes) {
        buffer.put(bytes, 0, bytes.length);
        buffer.flip();//need flip 
        return buffer.getLong();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章