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
Binding a Wpf Combobox to a Custom List
How to Save/Restore Serializable Object To/From File
How Expensive Are Exceptions in C#
Why Must "Stride" in the System.Drawing.Bitmap Constructor Be a Multiple of 4
Wix Installer Msi Not Installing the Winform App Created With Visual Studio 2017
Covariance and Contravariance Real World Example
Deciding Between Httpclient and Webclient
How to Monitor Clipboard Changes in C#
How to Handle Wndproc Messages in Wpf
Sharing Sessions Across Applications Using the ASP.NET Session State Service
Use Linq to Get Items in One List≪≫, That Are Not in Another List≪≫
How Does Having a Dynamic Variable Affect Performance
How to Convert a Datatable into a Generic List
Why Does C# Forbid Generic Attribute Types
How to Delete an Element from an Array in C#