Java - Integer toString(int i, int radix) 方法



描述

Java Integer toString(int i, int radix) 方法返回第一個引數i 的字串表示形式,其基數由第二個引數radix 指定。如果radix 小於 Character.MIN_RADIX 或大於 Character.MAX_RADIX,則使用基數 10。

以下 ASCII 字元用作數字:0123456789abcdefghijklmnopqrstuvwxyz

宣告

以下是java.lang.Integer.toString() 方法的宣告

public static String toString(int i, int radix)

引數

  • i − 這是要轉換的整數。

  • radix − 這是字串表示形式中使用的基數。

返回值

此方法返回引數在指定基數中的字串表示形式。

異常

以十進位制格式獲取正整數的字串表示形式示例

以下示例演示瞭如何使用 Integer toString(int i, int radix) 方法獲取指定 int 值的十進位制字串表示形式。我們建立了一個 int 變數併為其賦值一個正整數。然後使用 toString() 方法列印結果。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = 170;
      System.out.println("Number = " + i);
    
      /* returns the decimal string representation of the given number */
      System.out.println("toString = " + Integer.toString(i,10));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Number = 170
toString = 170

以八進位制格式獲取正整數的字串表示形式示例

以下示例演示瞭如何使用 Integer toString(int i, int radix) 方法獲取指定 int 值的八進位制字串表示形式。我們建立了一個 int 變數併為其賦值一個正整數。然後使用 toString() 方法列印結果。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = 170;
      System.out.println("Number = " + i);
    
      /* returns the octal string representation of the given number */
      System.out.println("toString = " + Integer.toString(i,8));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Number = 170
toString = 252

以十六進位制格式獲取正整數的字串表示形式示例

以下示例演示瞭如何使用 Integer toString(int i, int radix) 方法獲取指定 int 值的十六進位制字串表示形式。我們建立了一個 int 變數併為其賦值一個正整數。然後使用 toString() 方法列印結果。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = 170;
      System.out.println("Number = " + i);
    
      /* returns the hexadecimal string representation of the given number */
      System.out.println("toString = " + Integer.toString(i,16));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Number = 170
toString = aa

以二進位制格式獲取正整數的字串表示形式示例

以下示例演示瞭如何使用 Integer toString(int i, int radix) 方法獲取指定 int 值的二進位制字串表示形式。我們建立了一個 int 變數併為其賦值一個正整數。然後使用 toString() 方法列印結果。

package com.tutorialspoint;
public class IntegerDemo {
   public static void main(String[] args) {
      int i = 170;
      System.out.println("Number = " + i);
    
      /* returns the binary string representation of the given number */
      System.out.println("toString = " + Integer.toString(i,2));
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Number = 170
toString = 10101010
java_lang_integer.htm
廣告
© . All rights reserved.