天天看點

java double轉short_【轉】java byte轉long、double、float、int、short,或者long、double、float、int、short轉byte...

原文網址:http://www.xuebuyuan.com/988752.html

java byte與其他資料類型的轉換主要用于二進制資料的編碼和解碼,主要用于網絡傳輸,讀寫二進制檔案,java和c++伺服器之間的資料通信等等

以下是總結的源碼

protected int byteArrayToInt(byte[] b) {

return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8)

+ (b[3] & 0xFF);

}

protected int byteArrayToShort(byte[] b) {

return (b[0] << 8) + (b[1] & 0xFF);

}

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;

}

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;

}

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;

}

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));

}

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;

}

public static float byteArrayToFloat(byte[] v) {

ByteBuffer bb = ByteBuffer.wrap(v);

FloatBuffer fb = bb.asFloatBuffer();

return fb.get();

}

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;

}

public double byteArrayToDouble(byte[] b) {

ByteBuffer bb = ByteBuffer.wrap(b);

DoubleBuffer fb = bb.asDoubleBuffer();

return fb.get();

}