Programing

Java에서 int의 스트림을 char의 스트림으로 변환

lottogame 2020. 7. 22. 21:24
반응형

Java에서 int의 스트림을 char의 스트림으로 변환


이것은 아마도 다른 곳에서 대답되었을 것입니다. 그러나 int 값의 문자 값을 어떻게 얻습니까?

특히 tcp 스트림에서 a를 읽고 독자 .read () 메서드는 int를 반환합니다.

이것에서 숯을 어떻게 얻습니까?


스트림을 텍스트로 변환하려는 경우 사용할 인코딩을 알고 있어야합니다. 그런 다음 바이트 배열을 String생성자에 전달하고을 제공 Charset하거나 대신 InputStreamReader적절한 Charset것을 사용할 수 있습니다 .

간단히에서 캐스팅 intchar당신이 ISO-8859-1을 원하는 경우 읽고있는 직접 스트림에서 바이트 경우에만 작동합니다.

편집 : 당신이하면 되는 이미를 사용하여 Reader다음의 반환 값 캐스팅, read()char(그것의 -1 여부 확인 후) 갈 수있는 올바른 방법입니다 ...하지만 일반적으로보다 효율적이고 편리 호출 read(char[], int, int)의 전체 블록을 읽고 한 번에 텍스트. 읽은 문자 수를 확인하려면 반환 값을 확인하는 것을 잊지 마십시오.


아마도 당신은 요구하고 있습니다 :

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

더 많은 정보: Character.toChars(int codePoint)

지정된 문자 (유니 코드 코드 포인트)를 char 배열에 저장된 UTF-16 표현으로 변환합니다. 지정된 코드 포인트가 BMP (Basic Multilingual Plane 또는 Plane 0) 값인 경우 결과 char 배열의 값은 codePoint와 동일합니다. 지정된 코드 포인트가 보충 코드 포인트 인 경우 결과 문자 배열에는 해당 대리 쌍이 있습니다.


"int를 char로 변환"의 의미에 따라 다릅니다.

int에 값을 캐스트하고 싶다면 Java의 타입 캐스트 표기법을 사용하여 캐스트 할 수 있습니다.

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

정수 1을 문자 '1'로 변환하는 것을 의미한다면 다음과 같이 할 수 있습니다.

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

int 5를 char '5'로 간단히 변환하려면 : (정수 0-9에만 해당)

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

간단한 캐스팅 :

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

이것이 효과가없는 이유가 있습니까?


이 솔루션은 정수 길이 크기 = 1에서 작동합니다.

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

크기가 1보다 크면 for 루프를 사용하고 반복해야합니다.


여기에서 대부분의 답변은 바로 가기를 제안하며, 수행중인 작업을 모를 경우 큰 문제가 발생할 수 있습니다. 바로 가기를 사용하려면 데이터가 어떤 인코딩인지 정확히 알아야합니다.

UTF-16

Java가 문서에서 문자에 대해 이야기 할 때마다 16 비트 문자에 대해 이야기합니다.

DataInputStream편리한 방법이있는를 사용할 수 있습니다 . 효율성을 높이려면로 포장하십시오 BufferedReader.

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

문제는 각각 readChar()실제로 2를 수행 read하고 하나의 16 비트 문자로 결합한다는 것입니다.

US-ASCII

US-ASCII는 1 문자를 인코딩하기 위해 8 비트를 예약합니다. ASCII 테이블은 128 개의 가능한 문자 만 설명하므로 1 비트는 항상 사용되지 않습니다.

이 경우 간단히 캐스트를 수행 할 수 있습니다.

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

확장 ASCII

UTF-8, Latin-1, ANSI 및 기타 여러 인코딩은 모두 8 비트를 사용합니다. 첫 번째 7 비트는 ASCII 테이블을 따르며 US-ASCII 인코딩의 것과 동일합니다. 그러나 8 번째 비트는 이러한 모든 인코딩에서 다른 문자를 제공합니다. 그래서 여기에 흥미로운 것들이 있습니다.

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.


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

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

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


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

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

참고URL : https://stackoverflow.com/questions/833709/converting-stream-of-ints-to-chars-in-java

반응형