Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在不调用Encoding.Unicode.GetBytes的情况下获取UTF-16字节_C#_Unicode_Bytearray_Bit Shift_Utf 16 - Fatal编程技术网

C# 在不调用Encoding.Unicode.GetBytes的情况下获取UTF-16字节

C# 在不调用Encoding.Unicode.GetBytes的情况下获取UTF-16字节,c#,unicode,bytearray,bit-shift,utf-16,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) (cod

我想用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;
        }
for(变量i=0;i>8)和0xFF);
//k是插入UTF-16编码字符串字节的偏移量
缓冲区[i*2+k]=高;
缓冲区[i*2+k+1]=低;
}
有一个超负荷的,你想做什么就做什么

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);
}
Encoding.Unicode.GetBytes(str,0,str.Length,buffer,k);
//或者,如果您需要在'for'循环中执行更复杂的操作
对于(变量i=0;i