How can I convert a char to int in Java?
The ASCII table is arranged so that the value of the character '9'
is nine greater than the value of '0'
; the value of the character '8'
is eight greater than the value of '0'
; and so on.
So you can get the int value of a decimal digit char by subtracting '0'
.
char x = '9';
int y = x - '0'; // gives the int value 9
Converting Integer to Character in Java
Character.forDigit(C, 10)
Try this, it should work.
Java implicit conversion between int and char
Just write the char conversion to ASCII code (below your statements)
int x = '0' + 1 - '5'
48 + 1 - 53 = -4
int y = '5' - 0 + '1'
53 - 0 + 49 = 102
int y = '5' - '0' + '1'
53 - 48 + 49 = 54
Notice it's consistent, each int remains int and each char converted to ASCII code
Java - Problem with casting an int to char
In addition to the other answers: If you know for sure that 0 <= k <= 9
, you can use
System.out.println((char)(k + '0'));
to print the 'charified' version of your integer.
If k < 0
or k > 9
, there isn't a single char (character) describing it. In that case, you'll have to use a string, which is basically an array of chars:
System.out.println(Integer.toString(k));
Converting a int to char and then back to int - doesn't give same result always
This is because, while an int
is 4 bytes, a char
is only 2 bytes. Thus, you can't represent all values in a char
that you can in an int
. Using a standard unsigned integer representation, you can only represent the range of values from 0
to 2^16 - 1 == 65535
in a 2-byte value, so if you convert any number outside that range to a 2-byte value and back, you'll lose data.
How to convert integer to char
Use Char(n + '0')
. This will add the ASCII offset of the 0
digit and fix the rest of the digits too. For example:
julia> a = 5
5
julia> Char(a+'0')
'5': ASCII/Unicode U+0035 (category Nd: Number, decimal digit)
Also note, timing with @time
is a bit problematic, especially for very small operations. It is better to use @btime
or @benchmark
from BenchmarkTools.jl .
Related Topics
Using Pairs or 2-Tuples in Java
Bounding Generics with 'Super' Keyword
Where Is Java_Home on MACos Mojave (10.14) to Lion (10.7)
How to Set Output Stream to Textarea
What Data Type to Use for Money in Java
How to Start/Stop/Restart a Thread in Java
How to Add a Filter Class in Spring Boot
Stale Element Reference: Element Is Not Attached to the Page Document
Loading Images from Jars for Swing HTML
Hibernate Opensession() VS Getcurrentsession()
Java - How to Find the Redirected Url of a Url
Maven Modules + Building a Single Specific Module
Why Java Classes Do Not Inherit Annotations from Implemented Interfaces
Using Sleep() for a Single Thread
How to Check If a Single Character Appears in a String