-2
public class test1 {
String testVar = "s";
String binary;
int decimal;

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

here is my code, It seems that this works with other letters but when its an string value "s", Error shows up

Exception in thread "main" java.lang.NumberFormatException: For input string: "s"

Op-Zyra
  • 45
  • 6
  • 4
    what value do you expect? – Iłya Bursov Apr 12 '17 at 04:35
  • 1
    Base 16 means *hex*, and only digits 0-9 and letters A-F (upper- or lowercase) are valid, optionally prefixed with a minus sign (`-`). – Andreas Apr 12 '17 at 04:35
  • Why do you think it should work for "s" ? – Vipin Apr 12 '17 at 04:35
  • It is also not really clear what you mean with "binary". You see, any information can be represented in 0s and 1s. Any string can be encoded (read about **encoding**), and then turned into binary; see http://stackoverflow.com/questions/4173951/string-to-binary-output-in-java for example. Long story short: it is really not clear what you are actually asking for. But I guess: it is something that you would normally learn by doing some studying. Not by trial and error. – GhostCat Apr 12 '17 at 08:32

3 Answers3

1

Similar to valid values for Decimal is

0-9 (you won't see A,B,C,etc in decimal),

for Hex, valid values are

0-9, A-F.

While "S" is not in the list.

phray2002
  • 425
  • 4
  • 9
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);
RBS
  • 207
  • 1
  • 11
0

Here is short code that uses Integer.toString(val,radix) to convert int into binary value:

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);
    }
Jay Smith
  • 2,331
  • 3
  • 16
  • 27