十六進位制轉換為十進位制的Java程式


題目要求:給定一個十六進位制數,編寫一個Java程式將其轉換為等效的十進位制數。十六進位制的基值為16,十進位制的基值為10。當我們將十六進位制轉換為十進位制時,基值16將變為10。

數字系統分為四種類型:二進位制、八進位制、十進位制和十六進位制。基值取決於數字系統中包含的位數。例如,二進位制系統只包含兩個數字0和1。因此,它的基值為2。

十六進位制數系統

它表示從0到9和A到F的數字。它總共有16個數字,其基值也為16。12A16、34B16、45C16是一些十六進位制的例子。在計算機中,顏色的程式碼通常以十六進位制形式編寫。

假設,我們必須儲存一個很大的十進位制值,如果我們將其儲存在二進位制數系統中,則二進位制字串可能會變得非常長。在這種情況下,我們可以使用十六進位制數系統,它可以將4位二進位制儲存為1位。這縮短了位的長度。

十進位制數系統

這是最常用的數字系統。它有從0到9的10個數字。因此,其基值為10。如果未提及數字的基值,則認為其為10。單個數字的權重為10的冪,每個數字的權重比前一個數字高10倍。例如,1010、43110、98010等。

十六進位制到十進位制的轉換

給定的十六進位制數為(54A)16。要將其轉換為十進位制,請將每個數字乘以16n-1(其中,n是數字的個數),如下所示:

(54A)16 = 5 * 163-1 + 4 * 162-1 + A * 161-1
		= 5 * 162  + 4 * 161 + 10 * 160  
		= 5 * 256 + 64 + 10 
		= 1280 + 74
		= 1354 

使用Integer.parseInt()方法

這是Integer類的靜態方法,它根據指定的基值返回十進位制值。它位於java.lang包中。

語法

Integer.parseInt("String", base); 

其中,

  • 字串 - 將要轉換的值。

  • 基數 - 給定值將根據指定的基數進行轉換。

示例

在這個例子中,我們將使用Integer.parseInt()方法將十六進位制轉換為十進位制。

public class Conversion {
   public static void main(String args[]) {  
      // Converting and storing hexadecimal value to dec1 and dec2 with base 16  
      int dec1 = Integer.parseInt("54A", 16);
      int dec2 = Integer.parseInt("41C", 16);
      System.out.println("Decimal value of given Hexadecimal: " + dec1);
      System.out.println("Decimal value of given Hexadecimal: " + dec2);
   }
}

執行此程式碼後,將顯示以下結果:

Decimal value of given Hexadecimal: 1354
Decimal value of given Hexadecimal: 1052

使用使用者定義的方法

在這種方法中,我們將定義一個使用者定義的方法。然後,我們將執行一個for迴圈,直到十六進位制數的長度。在這個迴圈中,我們將獲取字元,然後我們將應用轉換邏輯。

示例

以下示例是對上面討論的方法的實際說明。

public class Conversion {
   public static void cnvrt(String hexNum) {
      // storing all the hexadecimal digits to this string 
      String hexStr = "0123456789ABCDEF"; 
      // converting given argument to uppercase
      hexNum = hexNum.toUpperCase();   
      int dec = 0;  
      for (int i = 0; i < hexNum.length(); i++) {  
         char ch = hexNum.charAt(i); 
         // fetching characters sequentially 
         int index = hexStr.indexOf(ch); 
         // fetching index of characters  
         dec = 16 * dec + index; 
         // applying the logic of conversion 
      }
      System.out.println("Decimal value of given Hexadecimal: " + dec); 
   }
   public static void main(String args[]) {
      // calling the function with arguments
      cnvrt("54A"); 
      cnvrt("41C");  
   }
}

上述程式碼的輸出如下:

Decimal value of given Hexadecimal: 1354
Decimal value of given Hexadecimal: 1052

更新於:2024年7月31日

961 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.