0

I'm trying to convert the string values to integers, however whenever i do this, it gives me the ASCI value of the character instead of the actual typed string.

Example:

a user inputs "11101" on there keyboard to a string variable named binary

for(int i = 0; i < binary.length(); i++){
storage[i] = Integer.valueOf(binary.charAt(i));
}

if I look at the values of storage[i], i will see only the ASCI values of the numbers, and not the actual 1's or 0's

1
  • Why? You don't need an array to store an integer. Commented Dec 3, 2013 at 22:59

5 Answers 5

3

Use Integer.parseInt(str,radix) method.

int no=Integer.parseInt("11101",2);

//or

int no=Integer.parseInt("11101");
Sign up to request clarification or add additional context in comments.

1 Comment

I never knew about the radix before, thank you so much. I will get a great deal of use from this.
2

Try this:

for(int i = 0; i < binary.length(); i++){
    storage[i] = Integer.valueOf(binary.substring(i, i + 1));
}

Comments

2

This should do the trick.

storage[i] = Integer.parseInt( binary.charAt(i));

4 Comments

Except it will not fail on invalid input such as: 110011911
Thank you for the example, i had actually tried this one, but still got the same results, but thanks for the info :)
@PlexQ there was no mention of validation
It returns the asci value of the input, not the typed value
2
for(int i = 0; i < binary.length(); i++){
  storage[i] = Integer.parseInt(binary.charAt(i), 2);
}

Comments

0
for(int i = 0; i < binary.length(); i++){
    storage[i] = binary.charAt(i) - '0';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.