在java中将int流转换为char

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/833709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:00:25  来源:igfitidea点击:

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

javatypes

提问by Omar Kooheji

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

这可能已经在其他地方得到了回答,但是您如何获得 int 值的字符值?

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

具体来说,我正在从 tcp 流中读取 a,而 reader .read() 方法返回一个 int。

How do I get a char from this?

我如何从中获得一个字符?

采纳答案by Jon Skeet

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 Stringconstructor and provide a Charset, or use InputStreamReaderwith the appropriate Charsetinstead.

如果您尝试将流转换为文本,则需要知道要使用哪种编码。然后,您可以将一个字节数组传递给String构造函数并提供 a Charset,或者使用InputStreamReader适当的Charset代替。

Simply casting from intto charonly works if you want ISO-8859-1, if you're reading bytes from a stream directly.

如果您直接从流中读取字节,则仅当您需要 ISO-8859-1 时,简单地从intto 转换char才有效。

EDIT: If you arealready using a Reader, then casting the return value of read()to charis 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.

编辑:如果您已经使用了Reader,然后浇注的返回值read()char是去(检查它是否是-1或不是之后),以正确的方式...但它通常更有效,更方便的调用read(char[], int, int)来读的一整块一次文本。不要忘记检查返回值,看看有多少字符被读取。

回答by Yuval Adam

Simple casting:

简单铸造:

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

Is there any reason this is not working for you?

有什么理由这不适合你吗?

回答by ATorras

Maybe you are asking for:

也许你在问:

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

More info: Character.toChars(int codePoint)

更多信息: 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.

将指定的字符(Unicode 代码点)转换为其存储在 char 数组中的 UTF-16 表示。如果指定的代码点是 BMP(基本多语言平面或平面 0)值,则生成的字符数组具有与 codePoint 相同的值。如果指定的代码点是补充代码点,则生成的 char 数组具有相应的代理对。

回答by ATorras

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

这完全取决于传入数据的编码。

回答by Lovubuntu

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

这取决于您所说的“将 int 转换为 char”是什么意思。

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

如果您只是想转换 int 中的值,您可以使用 Java 的类型转换表示法转换它:

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:

如果您的意思是将整数 1 转换为字符 '1',您可以这样做:

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

回答by Ryan Anderson

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

如果您想简单地将 int 5 转换为 char '5' : (仅适用于整数 0 - 9)

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

回答by Dheeraj Varne

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

将 char 转换为 int 或 long 的答案是简单的转换。

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

例如:- 如果您想将 Char '0' 转换为 long。

Follow simple cast

按照简单的演员表

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

Done!!

完毕!!

回答by Guest89898989

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

回答by Spiker

This solution works for Integer length size =1.

此解决方案适用于整数长度大小 =1。

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

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

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

如果大小 >1,我们需要使用 for 循环并迭代。

回答by bvdb

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

UTF-16

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

每当 java 在其文档中谈论字符时,它都会谈论 16 位字符。

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

您可以使用 a DataInputStream,它具有方便的方法。为了提高效率,请将其包装在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.

问题是每个readChar()实际上都会执行 2read并将它们组合成一个 16 位字符。

US-ASCII

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.

US-ASCII 保留 8 位来编码 1 个字符。ASCII 表只描述了 128 个可能的字符,所以 1 位总是未使用的。

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

扩展 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.

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.

如果您是牛仔,并且您认为第 8 位无关紧要(即您不关心像 "à, é, ?, è, ? ...)这样的字符,那么您可以通过简单的演员表逃脱。

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 Stringusing a charset parameter.

使用byte[]缓冲区读取数据并String使用字符集参数将其转换为 a 。

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

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

您还可以使用可以使用InputStreamReader字符集参数实例化的 。

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

还有一个黄金法则:永远不要直接将字节转换为字符。那总是一个错误。