Home >Backend Development >C++ >How Can I Convert Strings to Byte Arrays in .NET without Encoding?

How Can I Convert Strings to Byte Arrays in .NET without Encoding?

Barbara Streisand
Barbara StreisandOriginal
2025-02-01 05:21:09525browse

How Can I Convert Strings to Byte Arrays in .NET without Encoding?

Direct String-to-Byte Array Conversion in .NET

Frequently, .NET developers need to convert strings into byte arrays. The default UTF-16 encoding in .NET can be problematic when dealing with strings using different character encodings. This article presents a method to obtain the raw byte representation of a string without explicit encoding.

Byte Representation without Encoding

This technique directly copies the string's character data into a byte array, bypassing character encoding:

<code class="language-csharp">static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}</code>

Because .NET characters are 16-bit Unicode, the byte array's size is str.Length * sizeof(char) (character count multiplied by 2 bytes per character).

String Reconstruction from Bytes

To recreate the original string:

<code class="language-csharp">static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}</code>

This mirrors the conversion process, copying bytes back to a character array and creating a string.

Benefits of this Method

This approach offers several key benefits:

  • Encoding Agnostic: No need to specify an encoding; bytes directly represent Unicode characters.
  • Robust Error Handling: Handles invalid characters without errors; bytes are treated as raw data.
  • Intra-System Efficiency: Ideal for same-system communication, maximizing efficiency and preventing encoding discrepancies.

The above is the detailed content of How Can I Convert Strings to Byte Arrays in .NET without Encoding?. 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