2017-04-12 426 views
-2
public class test1 { 
String testVar = "s"; 
String binary; 
int decimal; 

public test1() 
{ 
    decimal = Integer.parseInt(testVar.trim(), 16); 
    System.out.println(decimal); 
} 

這裏是我的代碼,看來,這個工作與其他字母,但是當它是一個字符串值「S」,錯誤顯示出來轉換字符串「s」爲二進制

異常線程「main 「java.lang.NumberFormatException:對於輸入字符串: 」S「

+4

你期望什麼樣的價值? –

+1

基數16表示*十六進制*,只有數字0-9和字母A-F(大寫或小寫)有效,可選地以一個負號('-')作爲前綴。 – Andreas

+0

你爲什麼認爲它應該適用於「s」? – Vipin

回答

1

爲十進制有效值類似的

0-9(你不會SE êA,B,C等在十進制),

爲十六進制,有效值是

0-9,A-F。

雖然「S」不在列表中。

+0

感謝它飛過我的大腦,十六進制不是所有的字母字符 –

0
String inputString = "My String"; 
    byte[] bytes = inputString.getBytes("UTF-8"); 
    String binaryString = ""; 
    for (byte b : bytes) { 
     binaryString+=Integer.toBinaryString(b); 
    } 
    System.out.println(binaryString); 
0

下面是一個使用Integer.toString(VAL,基數)爲INT轉換成二進制值短代碼:

public static void main(String[] args) { 
     StringBuilder finalString = new StringBuilder(); 
     char[] arr= {'a','b','c'}; 
     for(int i = 0;i<arr.length;i++){ 
      int tempChar = arr[i]; 
      finalString.append(Integer.toString(tempChar,2)).append(",");//& this is not allowed then now only you need to create function for integer to binary conversion. 
     } 
     System.out.println("Your byte String is\n"+finalString); 
    } 
相關問題