Convert base Numbers การแปลงเลขฐาน
ในบทความนี้จะมีการแปลงเลขฐาน 6 แบบด้วยกัน คือ
อธิบายไฟล์ต่างๆที่ดาวโหลดมา
- ฐาน 10 เป็น ฐาน 2
- ฐาน 10 เป็น ฐาน 16
- ฐาน 2 เป็น ฐาน 10
- ฐาน 2 เป็น ฐาน 16
- ฐาน 2 เป็น ฐาน 16
- ฐาน 10 เป็น ฐาน 16
Panel footer
- ไฟล์ ConvertBaseNumbers.java คือ คลาสที่รวมเมเธตสำหรับแปลงเลขฐานทั้ง 6 แบบที่ได้กล่าวไว้ข้างต้น
import java.math.BigInteger;
public class ConvertBaseNumbers {
public ConvertBaseNumbers(){}
//bin
public String decTobin(String decimal){
return new BigInteger(decimal, 10).toString(2);
}
public String hexTobin(String hex){
return new BigInteger(hex, 16).toString(2);
}
//Dec
public String binToDec(String bin){
return String.valueOf(Integer.parseInt(bin, 2));
}
public String hexToDec(String hexadecimal){
return String.valueOf(Integer.parseInt(hexadecimal, 16));
}
//hex
public String binTohex(String bin){
String hex = new BigInteger(bin, 2).toString(16);
return hex;
}
public String decTohex(String dec){
return Integer.toHexString(Integer.parseInt(dec));
}
}
- ไฟล์ TestConvertBaseNumbers.java คือ ไฟล์สำหรับทดสอบการแปลงเลขฐานแบบต่างๆทั้ง 6 แบบ
public class TestConvertBaseNumbers {
static String bin,hex,dec;
public static void main(String [] args){
ConvertBaseNumbers covert = new ConvertBaseNumbers();
//input dec
String numberDecimal = "12";
System.out.println("Input Decimal Number : "+numberDecimal);
//dec
bin = covert.decTobin(numberDecimal);
System.out.println("decTobin : "+bin);
hex = covert.decTohex(numberDecimal);
System.out.println("decTohex : "+hex);
//bin
dec = covert.binToDec(bin);
System.out.println("binToDec : "+dec);
hex = covert.binTohex(bin);
System.out.println("binTohex : "+hex);
//hex
bin = covert.hexTobin(hex);
System.out.println("hexTobin : "+bin);
dec = covert.hexToDec(hex);
System.out.println("hexToDec : "+dec);
}
}
สรุป
การแปลงเลขฐานในภาษาจาวา มีคลาสให้เรียกใช้งานอยู่เราไม่จำต้องเขียนโปรแกรมคำนวณเอง ซึ่งอาจจะเป็นทางเลือกหนึ่งในการแปลงเลขฐาน ผมก็ขอจบการนำเสนอบทความแค่นี้ครับ (ขอบคุณที่อ่านถึงบรรทัดนี้ ฮ่าๆ)
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment