问题描述
我必须将char转换为字节或字节数组。在其他语言中,我知道一个字符只是一个字节。但是,查看Java Character类,其最小值为\\\ ,其最大值为\\\。这使得它看起来像一个char是2个字节长。
I must convert a char into a byte or a byte array. In other languages I know that a char is just a single byte. However, looking at the Java Character class, its min value is \u0000 and its max value is \uFFFF. This makes it seem like a char is 2 bytes long.
我可以将它存储为一个字节还是我需要将其存储为两个字节?
Will I be able to store it as a byte or do I need to store it as two bytes?
在任何人问之前,我会说,我想这样做,因为我在一个接口下工作,期望我的结果是一个字节数组。所以我必须把我的字符转换成一个。
Before anyone asks, I will say that I'm trying to do this because I'm working under an interface that expects my results to be a byte array. So I have to convert my char to one.
请让我知道,并帮助我理解这一点。
Please let me know and help me understand this.
谢谢,
jbu
Thanks,jbu
推荐答案
要将字符转换为字节,您需要指定。一些字符编码每个字符使用一个字节,而其他字符编码使用两个或多个字节。事实上,对于许多语言,有太多的字符要用单个字节编码。
To convert characters to bytes, you need to specify a character encoding. Some character encodings use one byte per character, while others use two or more bytes. In fact, for many languages, there are far too many characters to encode with a single byte.
在Java中,从字符转换为字节的最简单的方法是 String
class's 方法。但是,此方法将静默替换字符�如果字符不能在指定的编码下映射。如果您需要更多控制权,可以配置处理此错误或使用不同的替换字符。
In Java, the simplest way to convert from characters to bytes is with the String
class's getBytes(String encoding)
method. However, this method will silently replace characters with � if the character cannot be mapped under the specified encoding. If you need more control, you can configure a CharsetEncoder
to handle this case with an error or use a different replacement character.
这篇关于在Java中将char表示为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!