Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte[] to String with no encoding, no loss of data

Tags:

c#

.net

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?

like image 814
Craig Avatar asked Apr 12 '13 22:04

Craig


People also ask

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can you store a byte array as a string?

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.

How do you convert bytes to UTF-8?

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.


1 Answers

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);
}
like image 101
phoog Avatar answered Oct 12 '22 22:10

phoog