views:

6236

answers:

4

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?

+2  A: 

Simple casting:

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

Is there any reason this is not working for you?

Yuval A
Dangerous advice, if the text stream is not pure ASCII. See Jon Skeet's answer above.
sleske
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.
Vanuan
Sorry, I meant "from int to char"
Vanuan
+12  A: 

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.

Jon Skeet
+1 InputStreamReader does exactly what the OP is looking for.
Andrzej Doyle
Downvoters: please give reasons...
Jon Skeet
I think this is not what the OP is asking about. He is using Reader's read method: http://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.
Vanuan
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.
Jon Skeet
+4  A: 

Hi,

Maybe you are asking for:

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

More info: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#toChars(int)

ATorras
+1 I think you are right.
Vanuan
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.
Jon Skeet
Yeah, that's right, but an IAE would be thrown in that case.
ATorras
@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.
Jon Skeet
+1  A: 

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