I have an array of bytes. The 8-bit value of each byte is what I want as the characters in my String. You can think of my 8-bit values as ASCII, ANSI, UTF-8, ISO-8859-1, daily temperature readings, distance in inches from a point on a line, or whatever you want. It's irrelevant.
When I'm done. the char at position N in my String should have the same value as the byte at position N. That is, the high-order 8 bits should be 0 and the low order 8 bits should be the same as the source byte.
What Encoding do I use that simply maps bytes to chars with no change?
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
For text or character data, we use new String(bytes, StandardCharsets. UTF_8) to convert the byte[] to a String directly. However, for cases that byte[] is holding the binary data like the image or other non-text data, the best practice is to convert the byte[] into a Base64 encoded string.
In order to convert a String into UTF-8, we use the getBytes() method in Java. The getBytes() method encodes a String into a sequence of bytes and returns a byte array. where charsetName is the specific charset by which the String is encoded into an array of bytes.
For this requirement, I would dispense with encodings, because I don't know the details of what they do, and just convert the bytes myself.
string Convert(byte[] data)
{
char[] characters = data.Select(b => (char)b).ToArray();
return new string(characters);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With