‘>>’右移岩榆,低位舍棄
‘<<’左移,低位補(bǔ)0 相當(dāng)于*2
‘>>>’各薇,無(wú)符號(hào)右移
int a = 15; //1111
int b = a << 2;
int c = a >> 2;
int d = a >>> 2;
System.out.println("b = " + b + "\n" + "c = " + c + "\n" + "d = " + d);
b = 60
c = 3
d = 3
將long類(lèi)型轉(zhuǎn)換成byte數(shù)組,從高位取值在數(shù)組尾部向前插入
private static byte[] longToBytes(long a) {
byte[] bytes = new byte[8];
//尾部取高位
bytes[7] = (byte) (a & 0xff);
bytes[6] = (byte) (a >> 8 & 0xff);
bytes[5] = (byte) (a >> 16 & 0xff);
bytes[4] = (byte) (a >> 24 & 0xff);
bytes[3] = (byte) (a >> 32 & 0xff);
bytes[2] = (byte) (a >> 40 & 0xff);
bytes[1] = (byte) (a >> 48 & 0xff);
bytes[0] = (byte) (a >> 56 & 0xff);
System.out.println(Arrays.toString(bytes));
return bytes;
}
long n = 1001L;
byte[] n_bytes = longToBytes(n);
[0, 0, 0, 0, 0, 0, 3, -23]
同樣byte數(shù)組轉(zhuǎn)long類(lèi)型從數(shù)組頭部開(kāi)始去long的高位:
private static long bytesToLong(byte[] bytes){
return ((((long) bytes[0] & 0xff) << 56) | (((long) bytes[1] & 0xff) << 48)
| (((long) bytes[2] & 0xff) << 40) | (((long) bytes[3] & 0xff) << 32)
| (((long) bytes[4] & 0xff) << 24) | (((long) bytes[5] & 0xff) << 16)
|(((long) bytes[6] & 0xff) << 8) | (((long) bytes[7] & 0xff)));
}
System.out.println(" n = " + bytesToLong(n_bytes));
n = 1001
同理int占4個(gè)字節(jié)君躺,轉(zhuǎn)換方式如下:
private static byte[] intToBytes(int n){
byte[] bytes = new byte[4];
//尾部取高位
bytes[3] = (byte) (n & 0xff);
bytes[2] = (byte) (n >> 8 & 0xff);
bytes[1] = (byte) (n >> 16 & 0xff);
bytes[0] = (byte) (n >> 24 & 0xff);
System.out.println(Arrays.toString(bytes));
return bytes;
}
private static long bytesToInt(byte[] bytes){
return ((((long) bytes[0] & 0xff) << 24) | (((long) bytes[1] & 0xff) << 16)
| (((long) bytes[2] & 0xff) << 8) | (((long) bytes[3] & 0xff)));
}