Home >Backend Development >C++ >How Can I Convert a Byte Array to a String Without Using BinaryReader?

How Can I Convert a Byte Array to a String Without Using BinaryReader?

DDD
DDDOriginal
2025-01-17 09:22:12241browse

How Can I Convert a Byte Array to a String Without Using BinaryReader?

Convert byte array to string

In various programming scenarios, you may need to convert a byte array to a string representation. This conversion is critical when working with binary data or text information in byte-based formats.

Problem Statement

You have created a byte array containing two strings and want to convert them back to string form. However, you cannot use the BinaryReader class for this conversion.

Solution

Depending on the desired encoding, you can use System.Text.Encoding to achieve this conversion. The following code demonstrates how to convert a byte array to a string using the default system encoding:

<code class="language-csharp">var str = System.Text.Encoding.Default.GetString(result);</code>

This conversion assumes that the byte array contains UTF-16 encoded Unicode characters. If your data uses a different encoding, you can specify the encoding explicitly:

<code class="language-csharp">var encoding = System.Text.Encoding.GetEncoding("UTF-8");
var str = encoding.GetString(result);</code>

By using appropriate encoding, you can ensure that the resulting string accurately represents the contents of the byte array, thus preserving the original text information.

The above is the detailed content of How Can I Convert a Byte Array to a String Without Using BinaryReader?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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