将字符串转换为字节阵列而不使用编码(逐字节) [英] Converting a string to byte-array without using an encoding (byte-by-byte)

查看:513
本文介绍了将字符串转换为字节阵列而不使用编码(逐字节)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在字符串转换为字节[] 在.net中(C#)?

How do I convert a string to a byte[] in .NET (C#)?

另外,为什么要编码加以考虑?不能我只是得到什么字节字符串已经被存储在?为什么会出现在字符编码的依赖?

Also, why should encoding be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?

推荐答案

就像你所说,你的目标是,简单地说,来的得到了什么字节字符串已经被保存在的。照片 (而且,当然,为了能够重新构造从字节串。)

Contrary to the answers here, you DON'T need to worry about encoding if the bytes don't need to be interpreted!

Like you mentioned, your goal is, simply, to "get what bytes the string has been stored in".
(And, of course, to be able to re-construct the string from the bytes.)

只是这样做,而不是:

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;
}

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);
}

只要你的程序(或其他程序)不要尝试的跨preT 的字节不知何故,你显然没有提到你打算做的,再有就是< STRONG>什么不对这种方法!担心编码只是让你的生活更加复杂,没有真正的理由。

As long as your program (or other programs) don't try to interpret the bytes somehow, which you obviously didn't mention you intend to do, then there is nothing wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.

这将是连接codeD和DE codeD一样的,因为你的只看该字节的。

It will be encoded and decoded just the same, because you are just looking at the bytes.

如果你使用一个特定的编码,但是,它会一直给你带编码的麻烦/解码无效字符。

If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters.

这篇关于将字符串转换为字节阵列而不使用编码(逐字节)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆