Home > Backend Development > C++ > How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?

How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?

Susan Sarandon
Release: 2025-01-23 06:17:08
Original
163 people have browsed it

How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?

Conversion of string and byte array in C#

String to byte array conversion may cause problems when migrating code from VB to C#. This is especially true when dealing with properties of returned objects rather than byte arrays.

Consider the following problematic code:

<code class="language-csharp">if ((searchResult.Properties["user"].Count > 0))
{
    profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}</code>
Copy after login

The error encountered in this code stems from the expectation that the property value will be a byte array, when in fact it is an object. In order to solve this problem, it is important to understand the encoding used to convert the string to the byte array in the first place.

If the byte array was created using ASCII encoding, it should be converted back to a string using:

<code class="language-csharp">string someString = Encoding.ASCII.GetString(bytes);</code>
Copy after login

Similarly, if UTF8 encoding is used, the appropriate way to convert a byte array to a string is:

<code class="language-csharp">string someString = Encoding.UTF8.GetString(bytes);</code>
Copy after login

By identifying the encoding used to create the byte array, you can ensure that the string conversion is performed correctly.

The above is the detailed content of How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template