获取UTF-16字节而不调用Encoding.Unicode.GetBytes

时间:2013-10-23 17:20:04

标签: c# unicode bytearray bit-shift utf-16

我想用UTF-16编码字符串中的字节填充缓冲区的一部分而不分配中间字节数组(即不调用Encoding.Unicode.GetBytes(str)

假设我知道字符串只包含ASCII个字符,以下代码是否安全?

        for (var i = 0; i < str.Length; i++)
        {
            var code = char.ConvertToUtf32(str, i);

            var high = (byte) (code & 0xFF);
            var low = (byte) ((code >> 8) & 0xFF);

            //k is the offset where we insert bytes of the UTF-16 encoded string

            buffer[i*2 + k] = high;
            buffer[i*2 + k + 1] = low;
        }

1 个答案:

答案 0 :(得分:1)

GetBytes超载可以满足您的需要。

Encoding.Unicode.GetBytes(str, 0, str.Length, buffer, k);
// or, if you need to do something more complicated inside the `for` loop
for (var i = 0; i < str.Length; i++)
{
    Encoding.Unicode.GetBytes(str, i, 1, buffer, i*2 + k);
}