This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 2 years ago.
Given the following code:
char x = '5';
int a0 = x - '0'; // 0
int a1 = Integer.parseInt(x + ""); // 1
int a2 = Integer.parseInt(Character.toString(x)); // 2
int a3 = Character.digit(x, 10); // 3
int a4 = Character.getNumericValue(x); // 4
System.out.printf("%d %d %d %d %d", a0, a1, a2, a3, a4);
(version 4 credited to: casablanca)
What do you consider to be the "best-way" to convert a char into an int ? ("best-way" ~= idiomatic way)
We are not converting the actual numerical value of the char, but the value of the representation.
Eg.:
convert('1') -> 1
convert('2') -> 2
....
How about Character.getNumericValue?
I'd strongly prefer Character.digit.
The first method. It's the most lightweight and direct, and maps to what you might do in other (lower-level) languages. Of course, its error handling leaves something to be desired.
If speed is critical (rather than validation you can combine the result)
e.g.
char d0 = '0';
char d1 = '4';
char d2 = '2';
int value = d0 * 100 + d1 * 10 + d2 - '0' * 111;
Convert to Ascii then subtract 48.
(int) '7' would be 55
((int) '7') - 48 = 7
((int) '9') - 48 = 9
The best way to convert a character of a valid digit to an int value is below. If c is larger than 9 then c was not a digit. Nothing that I know of is faster than this. Any digits in ASCII code 0-9(48-57) ^ to '0'(48) will always yield 0-9. From 0 to 65535 only 48 to 57 yield 0 to 9 in their respective order.
int charValue = (charC ^ '0');
Related
I know this is trivial, but I can't find the proper explication. I have the following code
str="1230"
int rez=str.charAt(3) - '0';
rez=3;
How does this parsing work?
As long as the character is a digit, you can get the equivalent int value by subtracting '0'. The ASCII coding for '0' is decimal 48, '1' is decimal 49, etc.
So '8' - '0' = 56 - 48 = 8;
For your number, you can parse the entire string like this (assuming all the characters are digits, otherwise the result wouldn't make sense).
String v = "1230";
int result = 0; // starting point
for (int i = 0; i < v.length(); i++) {
result = result* 10 + v.charAt(i) -'0';
}
System.out.println(result);
Prints
1230
Explanation
In the above loop, first time thru
result = 0 * 10 + '1'-'0 = 1
second time thru
result = 1 * 10 + '2'-'0' = 12
third time thru
result = 12 * 10 + '3'-'0' = 123
last time thru
result = 123 * 10 + '0'-'0' = 1230
"Behind the scene" a char is just an int with a specific range (very simplified explanation).
Try following code to convince yourself:
System.out.println((int) '0'); // this won't output 0
System.out.println((int) 'a'); // this work as well
This is why arithmetic operations are possible on chars.
This question already has answers here:
Adding and subtracting chars, why does this work? [duplicate]
(4 answers)
Parentheses around data type?
(5 answers)
What does a 'int' in parenthesis mean when giving a value to an int?
(7 answers)
What is the purpose and meaning of (char)i or (int)i in java?
(3 answers)
Closed 2 years ago.
I encountered a similar piece of code:
public class print {
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
System.out.print((char) (i + 'a'));
}
}
}
If I run it, I get "abcdef".
My question regards this expression: (char) (i + 'a').
I kind of intuitively get what's going on, but I want a rigorous step-by-step explanation of how the computer translates it. As indicated in some answers, the char is simply a number displayed as a character. Fine, but what does this syntax with parentheses actually do? Is it a conversion? Can I use it for other types as well?
The ASCII value of a is 97.
When i = 0, i + 'a' = 0 + 97 => When cast into char, it will be a
When i = 1, i + 'a' = 1 + 97 => When cast into char, it will be b
When i = 2, i + 'a' = 2 + 97 => When cast into char, it will be c
...and so on
Java char is a 16-bit integral type. 'a' is the same as 97, which you can see with System.out.println((int) 'a'); - it follows that 98 is 'b' and so on across the entire ASCII table.
You can use char as an integer value and vise versa
Below code may help:
char aChar = 'a'; // a char
int aCharAscii = aChar; // 97
char bChar = 'a' + 1; // b char
int bCharAscii = aChar + 1; // 98
I have a simple block of code, can someone explain to me why this acceptable in Java?
int a = 10;
int c = 'A' + (a -1);
System.out.println(c);
The result of this displayed in compiler is: 74.
So where exactly the values of seventies come from?
Thanks for your answers.
In Java a char can be (explicitly or implicitly) casted to int, it then uses the ASCII value associated to this character.
It your case, the seventies comes from the character 'A'. The ASCII value of this character is 65. So the system implicitly does the casting 'A' → 65. Your calculation does:
c = 'A' + (a-1)
↓
c = 65 + (10-1)
↓
c = 74
The ascii value of 'A' is 65. Check this link for complete reference. The conversion occurs through (implicit) widening the char datatype to int datatype using its unicode value, which in this case for 'A' is 65 (jls 5.6.1).
Char is implicitly converted into integer resulting 'A' = 65
so 65+9 = 74
When you assign value of one data type to another, the two types might not be compatible with each other. It should be casted to correct type:
There are 2 types:-
Widening or Automatic Type Conversion.
which casts in this sequence:
byte -> short -> int -> long -> float -> double
char -> int
example :
int i = 100; //i is 100
float f = i; // f is 100.0
Narrowing or Explicit
Conversion. which casts in this sequence:
double -> float -> long -> int ->short -> byte
example:
double d = 100.100; //d is 100.100
int i = (int)d; //i is 100
So, When a Character value is used in integer context. It is automatically casted to int.
In your case:
int a = 10;
int c = 'A' + (a -1); //c = 65 + (10-1)
'A' ascii value is 65, thus you get c = 74
Hope this helps.
I'm working on this program that takes a binary string and converts it to decimal, using this guide to convert from binary to decimal. When I run through the for loop in my head, I get what the correct outputs would be. And yet, when I run my program, I get this strange output:
1
3
7
15
31
63
127
The actual output should look like this:
1
2
5
11
22
44
89
I cannot figure this out for the life of me. Why is my program doing this? Here's the current source code:
public class BinaryToDecimal
{
public static void main(String[] args)
{
String binary = "1011001";
int toMultiplyBy;
int decimalValue = 0;
for (int i = 1; i <= binary.length(); i++)
{
int whatNumber = binary.indexOf(i);
if (whatNumber == 0)
{
toMultiplyBy = 0;
}
else
{
toMultiplyBy = 1;
}
decimalValue = ((decimalValue * 2) + toMultiplyBy);
System.out.println(decimalValue);
}
}
}
Strings are 0 based so you should loop through the String from 0 to < the String's length, but indexOf(...), is not what you want to use since this will search for the location in the String of small ints which makes no sense. You don't care where the char equivalent of 2 is located in the String or even if it is in the String at all.
Instead you want to use charAt(...) or subString(...) and then parse to int. I would use
for (int i = 0; i < binary.length(); i++) {
int whatNumber = charAt(i) - '0'; // converts a numeric char into it's int
//...
To see what this is doing, create and run:
public class CheckChars {
public static void main(String[] args) {
String foo = "0123456789";
for (int i = 0; i < foo.length(); i++) {
char myChar = foo.charAt(i);
int actualIntHeld = (int) myChar;
int numberIWant = actualIntHeld - '0';
System.out.printf("'%s' - '0' is the same as %d - %d = %d%n",
myChar, actualIntHeld, (int)'0', numberIWant);
}
}
}
Which returns:
'0' - '0' is the same as 48 - 48 = 0
'1' - '0' is the same as 49 - 48 = 1
'2' - '0' is the same as 50 - 48 = 2
'3' - '0' is the same as 51 - 48 = 3
'4' - '0' is the same as 52 - 48 = 4
'5' - '0' is the same as 53 - 48 = 5
'6' - '0' is the same as 54 - 48 = 6
'7' - '0' is the same as 55 - 48 = 7
'8' - '0' is the same as 56 - 48 = 8
'9' - '0' is the same as 57 - 48 = 9
The numbers that represent the chars is based on the old ASCII table that gave each symbol a numeric representation. For more on this, please look here: ASCII Table
Two points:
Array indexing starts at zero, not 1, so your loop should be `for (int i=0; i
You are confusing indexOf() with substring(). In your case, binary.indexOf(i) does the following. First, the integer i is converted to a string. Then binary is searched left-to-right for a substring matching the string value of i. The first time through the loop i==1. This returns zero, because there's a 1 at index zero in binary. The second time, the value of i is 2. There's no 2 in binary, so this returns zero. For i==3, you're looking for a string 3 in binary, which will never be true.
Take a look at the String#substring() method, which is what I believe you intended.
How can I convert couple of characters to int, to keep the question simple let's assume this :
char c1 = '1';
char c2 = '4';
char c3 = '5';
What would be the efficient way to get 145 type int.
int myInt = Integer.parseInt(""+c1+c2+c3);
""+c1 gives you a String containing the char c1, to which you append the characters c2 and c3. Then you use parseInt() to convert it to an integer.
A more straightforward (but less robust) method would be this:
int myInt = 100*(c1-'0') + 10*(c2-'0') + (c3-'0');
c1-'0' gives you the number represented by c1 as opposed to the character code. Then you simply shift things to the correct decimal places and add.
int myInt = (c1 - '0') * 100 + (c2 - '0') * 10 + (c3 - '0');
Here is a more general method to convert a char array to int:
int valueOf(char[] input){
int result = 0;
for(char c : input) {
result *= 10;
result += Character.digit(c, 10);
}
return result;
}
The most correct way to convert a single digit character to an int is Character.digit(char ch, int radix), which can handle values in bases besides 10.
Strings are ultimately backed by a char[], so you could do the following:
char c1 = '1';
char c2 = '4';
char c3 = '5';
int converted = Integer.parseInt(new String(new char[]{c1, c2, c3}));
There are probably several other perfectly good ways to do this.