Home >Backend Development >C++ >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:
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!