Home > Backend Development > C++ > How to Convert Byte Arrays to Strings in C# Without Using BinaryReader?

How to Convert Byte Arrays to Strings in C# Without Using BinaryReader?

DDD
Release: 2025-01-17 09:06:13
Original
547 people have browsed it

How to Convert Byte Arrays to Strings in C# Without Using BinaryReader?

No need for BinaryReader in C# to convert byte array to string

When manipulating data in a byte array, it is often necessary to convert it to a string for further processing or display. This article explores how to perform this conversion using C# without relying on the BinaryReader class.

Question:

You have created a byte array containing one or more strings and need to retrieve the string value from the byte array. However, due to compatibility restrictions, the BinaryReader class cannot be used.

Solution:

To convert a byte array to a string, you can use the System.Text.Encoding.Default.GetString() method. This method takes a byte array as input and automatically determines the appropriate encoding based on the system's default settings.

<code class="language-csharp">byte[] result = reader.ReadBytes((int)binWriter.BaseStream.Length);
var str = System.Text.Encoding.Default.GetString(result);</code>
Copy after login

However, it is important to note that the default encoding may not always suit your specific needs. In this case, you can explicitly specify the desired encoding using one of the following methods:

<code class="language-csharp">// 使用 ASCII 编码转换
var str = System.Text.Encoding.ASCII.GetString(result);

// 使用 UTF-8 编码转换
var str = System.Text.Encoding.UTF8.GetString(result);

//等等</code>
Copy after login

The above is the detailed content of How to Convert Byte Arrays to Strings in C# Without Using BinaryReader?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template