Get the original byte representation of the string in C# (no specified encoding)
In contrast to the traditional suggestion, if the byte is not required, you can obtain the byte representation of the string in C# without designated codes. This method simplifies the process and ensures the consistency of byte representation.
For this reason, you can use
, as shown below: System.Buffer.BlockCopy
<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>
<code class="language-csharp">// 请勿对任意字节使用此函数;仅对相同系统上的 GetBytes 输出使用 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>
The above is the detailed content of How Can I Get the Raw Byte Representation of a C# String Without Specifying Encoding?. For more information, please follow other related articles on the PHP Chinese website!