Converting stream of int's to char's in java

JavaTypes

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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);
....
}

Solution 3 - Java

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.

Solution 4 - Java

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';

Solution 5 - Java

Simple casting:

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

Is there any reason this is not working for you?

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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();

Solution 9 - Java

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

Solution 10 - Java

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

Solution 11 - Java

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); 

Solution 12 - Java

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!!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmar KoohejiView Question on Stackoverflow
Solution 1 - JavaATorrasView Answer on Stackoverflow
Solution 2 - JavaLovubuntuView Answer on Stackoverflow
Solution 3 - JavaJon SkeetView Answer on Stackoverflow
Solution 4 - JavaRyan AndersonView Answer on Stackoverflow
Solution 5 - JavaYuval AdamView Answer on Stackoverflow
Solution 6 - JavaSpikerView Answer on Stackoverflow
Solution 7 - JavabvdbView Answer on Stackoverflow
Solution 8 - Javasrc3369View Answer on Stackoverflow
Solution 9 - JavaShwarz AndreiView Answer on Stackoverflow
Solution 10 - JavacarejView Answer on Stackoverflow
Solution 11 - JavaGuest89898989View Answer on Stackoverflow
Solution 12 - JavaDheeraj VarneView Answer on Stackoverflow