再presenting字符作为Java中的一个字节 [英] Representing char as a byte in Java

查看:105
本文介绍了再presenting字符作为Java中的一个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要一个字符转换为字节或字节数组。在其他语言中我知道,一个char只是一个字节。然而,看着Java字符类,它的最小值为\\ u0000的其最大值为\\ uFFFF。这使得它看起来像一个字符为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

推荐答案

要字符转换为字节,你需要指定一个字符编码。一些字符编码每个字符使用一个字节,而其他使用两个或多个字节。事实上,对于许多语言,有太多太多的字符EN code用一个字节。

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中,从字符转换成字节的最简单方法是使用字符串类的<​​一个href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#getBytes%28java.lang.String%29\"><$c$c>getBytes(String编码) 方法。但是,这种方法会悄悄地替换&#xfffd字符;如果字符无法在指定编码下进行映射。如果你需要更多的控制,您可以配置一个<一个href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/CharsetEn$c$cr.html\"><$c$c>CharsetEn$c$cr用一个错误来处理这种情况,或者使用不同的替换字符。

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.

这篇关于再presenting字符作为Java中的一个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆