一、十進制與二進制轉換
在Java中,可以通過以下代碼將十進制轉換成二進制:
int decimal = 10; // 十進制數 String binary = Integer.toBinaryString(decimal); // 轉換為二進制字符串 System.out.println("Binary: " + binary); // 打印結果:Binary: 1010
首先定義一個整數型變量decimal,並將它賦值為10,即為十進制數。接下來調用Integer類的toBinaryString方法,將十進制數轉換為二進制字符串,最後通過System.out.println方法輸出結果Binary: 1010。
反之,可以通過以下代碼將二進制轉換成十進制:
String binary = "1010"; // 二進制字符串 int decimal = Integer.parseInt(binary, 2); // 轉換為十進制數 System.out.println("Decimal: " + decimal); // 打印結果:Decimal: 10
與上述代碼類似,首先定義一個字符串型變量binary,並將它賦值為1010,即為二進制字符串。接下來調用Integer類的parseInt方法,將二進制字符串轉換為十進制數,最後通過System.out.println方法輸出結果Decimal: 10。
二、十進制與八進制轉換
可以通過以下代碼將十進制轉換成八進制:
int decimal = 10; // 十進制數 String octal = Integer.toOctalString(decimal); // 轉換為八進制字符串 System.out.println("Octal: " + octal); // 打印結果:Octal: 12
跟上述代碼類似,將toBinaryString方法修改為toOctalString方法即可將十進制數轉換為八進制字符串。
同樣地,也可以通過以下代碼將八進制轉換成十進制:
String octal = "12"; // 八進制字符串 int decimal = Integer.parseInt(octal, 8); // 轉換為十進制數 System.out.println("Decimal: " + decimal); // 打印結果:Decimal: 10
與上述代碼類似,將parseInt方法中的第二個參數修改為8即可將八進制字符串轉換為十進制數。
三、十進制與十六進制轉換
可以通過以下代碼將十進制轉換成十六進制:
int decimal = 10; // 十進制數 String hex = Integer.toHexString(decimal); // 轉換為十六進制字符串 System.out.println("Hexadecimal: " + hex); // 打印結果:Hexadecimal: a
同樣地,將toBinaryString方法修改為toHexString方法即可將十進制數轉換為十六進制字符串。
最後,可以通過以下代碼將十六進制轉換成十進制:
String hex = "a"; // 十六進制字符串 int decimal = Integer.parseInt(hex, 16); // 轉換為十進制數 System.out.println("Decimal: " + decimal); // 打印結果:Decimal: 10
同上述代碼類似,將parseInt方法中的第二個參數修改為16即可將十六進制字符串轉換為十進制數。
四、小結
Java中的進制轉換方法十分簡單,只需要調用相應的方法即可。但是需要注意的是,不同的進制所對應的字符串格式是不同的,需要根據實際情況進行轉換。進制轉換在Java編程中常常用到,對於程序員而言,掌握進制轉換的方法是必不可少的。
原創文章,作者:KMYUJ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/334557.html