This article introduces how to convert the C# string to byte array without specification without specified coding. This method avoids the complexity related to character coding.
Coding
It mainly plays a role when you want to interpret the byte array as a string. Different codes interpret the same bytes as different characters. By specifying the encoding, you can indicate that the system decodes bytes according to the specified encoding to generate specific character sequences.However, if you just want to store the bytes of the string word by word instead of the character explanation, you can simply copy the bit of the string character array to the byte array. This can be implemented through the following code:
To convert the byte array back to the string, please use:
<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>
This method ensures that the bytes of the original string are accurately retained without relying on coding. This method provides a reliable and convenient alternative encoding method as long as the byte goal goals are not required.
The above is the detailed content of How to Get a String's Byte Representation in C# Without Encoding?. For more information, please follow other related articles on the PHP Chinese website!