java byte與其他資料類型的轉換主要用於位元據的編碼和解碼,主要用於網路傳輸,讀寫二進位檔案,java和c++伺服器之間的資料通訊等等
以下是總結的源碼
/** * BYTE轉INT * * @param b * @return */ protected int byteArrayToInt(byte[] b) { return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF); }
/** * BYTE轉SHORT * * @param b * @return */ protected int byteArrayToShort(byte[] b) { return (b[0] << 8) + (b[1] & 0xFF); }
/** * SHORT轉BYTE資料 * * @param s * @return */ protected byte[] shortToByteArray(short s) { byte[] shortBuf = new byte[2]; for (int i = 0; i < 2; i++) { int offset = (shortBuf.length - 1 - i) * 8; shortBuf[i] = (byte) ((s >>> offset) & 0xff); } return shortBuf; }
/** * INT資料轉BYTE資料 * * @param i * @return */ protected byte[] intToByteArray(int i) { byte[] result = new byte[4]; result[0] = (byte) ((i >> 24) & 0xFF); result[1] = (byte) ((i >> 16) & 0xFF); result[2] = (byte) ((i >> 8) & 0xFF); result[3] = (byte) (i & 0xFF); return result; }
/** * 轉換long型為byte數組 * * @param bb * @param x * @param index */ public byte[] longToByteArray(long x, int index) { byte[] bb = new byte[8]; bb[index + 7] = (byte) (x >> 56); bb[index + 6] = (byte) (x >> 48); bb[index + 5] = (byte) (x >> 40); bb[index + 4] = (byte) (x >> 32); bb[index + 3] = (byte) (x >> 24); bb[index + 2] = (byte) (x >> 16); bb[index + 1] = (byte) (x >> 8); bb[index + 0] = (byte) (x >> 0); return bb; }
/** * 通過byte數組取到long * * @param bb * @param index * @return */ public long byteArrayToLong(byte[] bb, int index) { return ((((long) bb[index + 7] & 0xff) << 56) | (((long) bb[index + 6] & 0xff) << 48) | (((long) bb[index + 5] & 0xff) << 40) | (((long) bb[index + 4] & 0xff) << 32) | (((long) bb[index + 3] & 0xff) << 24) | (((long) bb[index + 2] & 0xff) << 16) | (((long) bb[index + 1] & 0xff) << 8) | (((long) bb[index + 0] & 0xff) << 0)); } /** * float轉換byte * * @param bb * @param x * @param index */ public static byte[] floatTobyteArray(float v) { ByteBuffer bb = ByteBuffer.allocate(4); byte[] ret = new byte[4]; FloatBuffer fb = bb.asFloatBuffer(); fb.put(v); bb.get(ret); return ret; } /** * 通過byte數組取得float * * @param bb * @param index * @return */ public static float byteArrayToFloat(byte[] v) { ByteBuffer bb = ByteBuffer.wrap(v); FloatBuffer fb = bb.asFloatBuffer(); return fb.get(); }
/** * double轉換byte * * @param bb * @param x * @param index */ public byte[] doubleToByteArray(double x) { ByteBuffer bb = ByteBuffer.allocate(8); byte[] ret = new byte[8]; DoubleBuffer fb = bb.asDoubleBuffer(); fb.put(x); bb.get(ret); return ret; }
/** * 通過byte數組取得float * * @param bb * @param index * @return */ public double byteArrayToDouble(byte[] b) { ByteBuffer bb = ByteBuffer.wrap(b); DoubleBuffer fb = bb.asDoubleBuffer(); return fb.get(); }