2017-04-12 219 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); 
    } 
相关问题