How to Convert Byte Array to String

How to convert byte array to string and vice versa?

Your byte array must have some encoding. The encoding cannot be ASCII if you've got negative values. Once you figure that out, you can convert a set of bytes to a String using:

byte[] bytes = {...}
String str = new String(bytes, StandardCharsets.UTF_8); // for UTF-8 encoding

There are a bunch of encodings you can use, look at the supported encodings in the Oracle javadocs.

convert a byte array to string

You could convert the byte array to a char array, and then construct a string from that

scala> val bytes = Array[Byte]('a','b','c','d')
bytes: Array[Byte] = Array(97, 98, 99, 100)

scala> (bytes.map(_.toChar)).mkString
res10: String = abcd

scala>

How to convert byte array to string

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);

Convert byte array to string in C#

Try string x = Encoding.UTF8.GetString(readData.payload, 1, readData.payload.Length - 1);

Last argument is count, so if you start from 1, count has to be 1 less.

How to Convert Byte Array back into string?

If s is that byte string:

for x in s:
print(f'{x:08b}')

Instead of print, you can do what you like with the strings of 0's and 1's.

It is unnecessarily inefficient to go through strings of 0 and 1 characters for encoding and decoding. You should instead assemble and disassemble the bytes directly using the bit operators (<<, >>, |, &).



Related Topics



Leave a reply



Submit