計算機只能識別二進制數,在實際應用中存在十進制、八進制和十六進制數。Java中提供了對應的API來實現進制轉換。
- 十進制數轉換成其他進制數。
//十進制數轉換成二進制、十六進制、八進制
System.out.println(Integer.toBinaryString(112));
System.out.println(Integer.toHexString(112));
System.out.println(Integer.toOctalString(112));
//二進制、八進制、十六進制轉換成十進制
System.out.println(Integer.parseInt("111001", 2));
System.out.println(Integer.parseInt("27", 8));
System.out.println(Integer.parseInt("A8", 16));
基本數據類型轉換成字節數組
例如8143二進制數爲00000000 00000000 00011111 11001111
第一個小端字節:8143 >>0*8 &&0xff = 11001111,無符號數則爲207,有符號數爲11001111–>11001110–>00110001 爲-49。
第二個小端字節:8143>>1*8 &&0xff = 00011111 = 31
第三個小端字節:8143>>2*8 &&0xff = 00000000 = 0
第四個小端字節: 8143>>3*8 &&0xff = 00000000 = 0小端是指低位字節位於低地址端即爲起始地址,高位字節位於高地址端。大端則剛好相反。
字符串轉換成字節數組
String str;
byte[] bytes = str.getBytes();
- 字節數組轉換成字符串
byte[] bytes = new byte[N];
String s = new String(bytes);
String s = new String(bytes, encode); //encode 爲utf-8,gb2312等
//整型轉換成byte數組
private static byte[] Int2Bytes(int n) {
byte[] bytes = new byte[4];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) ((n >> (i * 8)) & 0xff);
}
return bytes;
}
//byte數組轉換成整型
private static int Bytes2Int(byte[] bytes) {
int result = 0;
for (int i = 0; i < bytes.length; i++) {
result += ((bytes[i] & 0xff) << i * 8);
}
return result;
}