简体   繁体   English

将Java byte []解释为字符串

[英]Interpret Java byte[] as a String

I have an array of bytes b: 我有一个字节数组b:

b = [-98, -99]

I need to pass this segment of data to a function. 我需要将此数据段传递给函数。 The function takes a String (this is not changeable). 该函数采用字符串(不可更改)。 How do I get Java to interpret the raw binary data in b as a string without changing any of the bits in b 如何使Java将b中的原始二进制数据解释为字符串而不更改b中的任何位

EDIT 编辑

This is not a repeat of: 这不是以下内容的重复:

Converting byte array to String (Java) 将字节数组转换为字符串(Java)

Because, the array b consists of the bits [1001 1110 1001 1101] or [9E9D]. 因为,数组b由[1001 1110 1001 1101]或[9E9D]位组成。 If I use 如果我用

String str = new String(b, "Cp1252")

The Cp1252 encoding does not have a value for the seqeuence of bits 1001 1101 or 9D. Cp1252编码没有位1001 1101或9D序列的值。 So this function results in the the str = "ž?". 因此,此函数将导致str =“ž?”。 Which in binary form is [1001 1110 0011 1111] or [9E3F]. 二进制格式为[1001 1110 0011 1111]或[9E3F]。 Notice the function has changed my bits, which essentially corrupts my data. 注意,该函数更改了我的位,这实际上破坏了我的数据。

I think this would be done in C++ using a reinterpret cast but no such thing exists in java. 我认为这将使用重新解释的强制转换在C ++中完成,但Java中不存在此类内容。 Thanks in advance. 提前致谢。

You probably want something like new String(b, "charset")); 您可能想要诸如new String(b, "charset")); where charset is replaced by the encoding you want to use. charset由您要使用的编码替换。 I would suggest UTF-8 , except your values aren't valid UTF-8. 我建议使用UTF-8 ,除非您的值不是有效的UTF-8。

You cannot do this with arbitrary bytes of any value, as there is no encoding that will allow that, and I'm assuming you have no control over the decoding of the data. 您无法使用任何值的任意字节来执行此操作,因为没有编码将允许这样做,并且我假设您无法控制数据的解码。 If you do have control over the decoding as well as the encoding, you could write your own Charset so that you can map the data into and back out of a normal Java string, which is encoded as UTF-16. 如果您确实可以控制解码和编码,则可以编写自己的字符集,以便可以将数据映射到普通Java字符串(映射为UTF-16)中,也可以映射出该字符串。 To encode it: 对其进行编码:

String str = new String(byteBuffer, MyCharSet);

To decode it: 解码:

byte[] byteBuffer = str.getBytes(MyCharSet);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM