Omar Kooheji
Omar Kooheji

Reputation: 55800

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

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?

Upvotes: 114

Views: 370864

Answers (12)

Shwarz Andrei
Shwarz Andrei

Reputation: 707

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

Upvotes: 1

ATorras
ATorras

Reputation: 4313

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.

Upvotes: 144

src3369
src3369

Reputation: 2049

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

Upvotes: 1

bvdb
bvdb

Reputation: 24800

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.

Upvotes: 1

Spiker
Spiker

Reputation: 111

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.

Upvotes: 4

Guest89898989
Guest89898989

Reputation: 9

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

Upvotes: 0

Dheeraj Varne
Dheeraj Varne

Reputation: 203

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

Upvotes: -2

Ryan Anderson
Ryan Anderson

Reputation: 291

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

Upvotes: 28

Lovubuntu
Lovubuntu

Reputation: 1051

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

Upvotes: 105

Jon Skeet
Jon Skeet

Reputation: 1504122

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.

Upvotes: 72

carej
carej

Reputation:

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

Upvotes: 0

Yuval Adam
Yuval Adam

Reputation: 165340

Simple casting:

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

Is there any reason this is not working for you?

Upvotes: 8

Related Questions