简体   繁体   中英

Interpret Java byte[] as a String

I have an array of bytes 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

EDIT

This is not a repeat of:

Converting byte array to String (Java)

Because, the array b consists of the bits [1001 1110 1001 1101] or [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. So this function results in the the str = "ž?". Which in binary form is [1001 1110 0011 1111] or [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. Thanks in advance.

You probably want something like new String(b, "charset")); where charset is replaced by the encoding you want to use. I would suggest UTF-8 , except your values aren't valid 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. To encode it:

String str = new String(byteBuffer, MyCharSet);

To decode it:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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