114

This has probably been answered else where but how do you get the character value of an int value?

Specifically I'm reading a from a tcp stream and the readers .read() method returns an int.

How do I get a char from this?

4
  • 1
    You didn't elaborate on what data are you sending and reading. Do you send binary bytes or Unicode characters? The readers .read() method returns an int. Yes, but it returns the character read, as an integer in the range 0 to 65535 (or -1, this is because I think int used instead of char). Maybe just using public int read(char[] cbuf) will solve the problem? Commented May 7, 2009 at 10:36
  • The answers for this question do not work for JSP Java. If you are using jsp's, see this stack overflow bug: stackoverflow.com/questions/4621836/… Commented Nov 13, 2013 at 16:32
  • I think this is a valid question. One of the difficulties from converting an integer to a char, is dealing with negative values and values >= 255. Commented Jun 26, 2014 at 13:43
  • What if I want to convert a byte that is in a byte array to a character and then print it to the console? Commented Jul 8, 2014 at 14:29

12 Answers 12

144

Maybe you are asking for:

Character.toChars(65) // returns ['A']

More info: Character.toChars(int codePoint)

Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array. If the specified code point is a BMP (Basic Multilingual Plane or Plane 0) value, the resulting char array has the same value as codePoint. If the specified code point is a supplementary code point, the resulting char array has the corresponding surrogate pair.

Sign up to request clarification or add additional context in comments.

3 Comments

That's only valid if the integer in question is already a UTF-16 code point. We have no idea whether that's the case.
@Atec: No, my point is that if he's just reading bytes from a stream (it's not clear) then converting by just casting or using toChars is usually inappropriate. If he's reading from a Reader, then it's fine.
While admittedly the question didn't specify it, this question comes up as the first result in a Google search for converting ASCII code points to chars, so I'm upvoting it.
105

It depends on what you mean by "convert an int to char".

If you simply want to cast the value in the int, you can cast it using Java's typecast notation:

int i = 97; // 97 is 'a' in ASCII
char c = (char) i; // c is now 'a'

If you mean transforming the integer 1 into the character '1', you can do it like this:

if (i >= 0 && i <= 9) {
char c = Character.forDigit(i, 10);
....
}

2 Comments

What if you were going from Char to Integer? Integer.parseInt(c)?
This answer is THE one :-)
72

If you're trying to convert a stream into text, you need to be aware of which encoding you want to use. You can then either pass an array of bytes into the String constructor and provide a Charset, or use InputStreamReader with the appropriate Charset instead.

Simply casting from int to char only works if you want ISO-8859-1, if you're reading bytes from a stream directly.

EDIT: If you are already using a Reader, then casting the return value of read() to char is the right way to go (after checking whether it's -1 or not)... but it's normally more efficient and convenient to call read(char[], int, int) to read a whole block of text at a time. Don't forget to check the return value though, to see how many characters have been read.

5 Comments

I think this is not what the OP is asking about. He is using Reader's read method: java.sun.com/j2se/1.4.2/docs/api/java/io/Reader.html#read() The question he is asking is how to convert value returned by this method into char.
If he's genuinely using Reader, that certainly makes a difference. It's not clear, given that he talks about a stream and a reader (with a lower case r) in the same sentence :( Have edited my answer to make this clear.
you can also wrap the InputStreamReader in a BufferedReader, as mentioned in the javadoc docs.oracle.com/javase/8/docs/api/java/io/…
Why is it that "Simply casting from int to char only works if you want ISO-8859-1" ? Is it because Java uses UTF-16 internally, and all ISO-8859-1 characters keep the same code unit (bits) in UTF-16 ?
@Sebastien: Yes, that's basically it.
28

If you want to simply convert int 5 to char '5': (Only for integers 0 - 9)

int i = 5;
char c = (char) ('0' + i); // c is now '5';

3 Comments

No.. '0' + 5 becomes the string '05'. Right-hand side should be (char) ((int) '0') + i;
Not true because characters don't get converted to Strings in Java.
+1 -- tried and tested, it works! Try and test it yourself, seemingly unlike the commenters here...
8

Simple casting:

int a = 99;
char c = (char) a;

Is there any reason this is not working for you?

4 Comments

Dangerous advice, if the text stream is not pure ASCII. See Jon Skeet's answer above.
It might not work. But I think it would actually. The char data type stores UTF-16 coded value. So to cast char to int you need to do some transformations. But since the OP uses read() method which already returns UTF-16 coded value simple casting would work I think. Correct me if I wrong.
Sorry, I meant "from int to char"
this will cause unexpected encoding values, not numbers
4

This solution works for Integer length size =1.

Integer input = 9; Character.valueOf((char) input.toString().charAt(0))

if size >1 we need to use for loop and iterate through.

Comments

1

Most answers here propose shortcuts, which can bring you in big problems if you have no idea what you are doing. If you want to take shortcuts, then you have to know exactly what encoding your data is in.

UTF-16

Whenever java talks about characters in its documentation, it talks about 16-bit characters.

You can use a DataInputStream, which has convenient methods. For efficiency, wrap it in a BufferedReader.

// e.g. for sockets
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
char character = readChar(); // no need to cast

The thing is that each readChar() will actually perform 2 read's and combine them to one 16-bit character.

US-ASCII

US-ASCII reserves 8 bits to encode 1 character. The ASCII table only describes 128 possible characters though, so 1 bit is always unused.

You can simply perform a cast in this case.

int input = stream.read();
if (input < 0) throw new EOFException();
char character = (char) input;

Extended ASCII

UTF-8, Latin-1, ANSI and many other encodings use all 8-bits. The first 7-bit follow the ASCII table and are identical to the ones of the US-ASCII encoding. However, the 8th bit offers characters that are different in all these encodings. So, here things get interesting.

If you are a cowboy, and you think that the 8th bit does not matter (i.e. you don't care about characters like "à, é, ç, è, ô ...) then you can get away with a simple cast.

However, if you want to do this professionally, you should really ALWAYS specify a charset whenever you import/export text (e.g. sockets, files ...).

Always use charsets

Let's get serious. All the above options are cheap tricks. If you want to write flexible software you need to support a configurable charset to import/export your data. Here's a generic solution:

Read your data using a byte[] buffer and to convert that to a String using a charset parameter.

byte[] buffer = new byte[1024];
int nrOfBytes = stream.read(buffer);
String result = new String(buffer, nrOfBytes, charset);

You can also use an InputStreamReader which can be instantiated with a charset parameter.

Just one more golden rule: don't ever directly cast a byte to a character. That's always a mistake.

Comments

1

Basing my answer on assumption that user just wanted to literaaly convert an int to char , for example

Input: 
int i = 5; 
Output:
char c = '5'

This has been already answered above, however if the integer value i > 10, then need to use char array.

char[] c = String.valueOf(i).toCharArray();

Comments

1
    int i = 7;
    char number = Integer.toString(i).charAt(0);
    System.out.println(number);

Comments

0

This is entirely dependent on the encoding of the incoming data.

2 Comments

this is such as useless "answer", i'd down vote but it ain't even worth it.
@Lpc_dark This answer is more correct that 90% of the other answers. See my answer for more details.
0

maybe not the fastest one:

//for example there is an integer with the value of 5:
int i = 5;

//getting the char '5' out of it:
char c = String.format("%s",i).charAt(0); 

Comments

-2

The answer for conversion of char to int or long is simple casting.

For example:- if you would like to convert Char '0' into long.

Follow simple cast

Char ch='0';
String convertedChar= Character.toString(ch);  //Convert Char to String.
Long finalLongValue=Long.parseLong(convertedChar);

Done!!

1 Comment

thats EXACTLY the opposite of what he was asking.

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.