Home >Backend Development >C++ >How Can I Get the Raw Byte Representation of a String in C# Without Encoding?
Code and bytes of string in C#indicate
However, if your purpose is to obtain the underlying bytes of the string without explanation, there is a simple solution:
<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; } // 仅限于在同一系统上GetByte方法的输出上使用,不要在任意字节上使用 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 method is regarded as a byte sequence without any coding considerations. It allows you to retrieve and rebuild strings from its bytes, without relying on specific codes.
It should be noted that this method is only applied to scenarios that do not need byte interpretation. Try to interpret these bytes as different codes may cause errors or data damage.
The above is the detailed content of How Can I Get the Raw Byte Representation of a String in C# Without Encoding?. For more information, please follow other related articles on the PHP Chinese website!