Home >Backend Development >C++ >How Can I Get the Raw Byte Representation of a String in C# Without Encoding?

How Can I Get the Raw Byte Representation of a String in C# Without Encoding?

DDD
DDDOriginal
2025-02-01 05:11:09965browse

How Can I Get the Raw Byte Representation of a String in C# Without Encoding?

Code and bytes of string in C#indicate

When processing the string in C#, the character code must be considered, especially when converting the string to byte array. The encoding allows the string is represented by different character sets, such as Unicode UTF-8 or ASCII.

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!

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