日期:2014-05-17  浏览次数:21099 次

c++转换C#问题,立马给分
我在翻译C++代码成C#的时候,遇到翻译不过去的情况,以下是C++代码:
int CResponseEvdo::DecodeUCS2( BYTE pdu[], int nInLength,CString& message)
{
if(!message.IsEmpty())
{
message.Empty();
}
for(int i=0;i<nInLength;i++)
{
WCHAR lTemp =pdu[i*2]*256+pdu[i*2+1];
message+=lTemp;
}
return (message.GetLength());
}

我翻译成C#的代码如下:
 private string DecodeUCS2(byte[] text, int length)
        {
            byte[] bytes = new byte[512];
            byte[] bBytes = new byte[512];
            Buffer.BlockCopy(text, 0, bytes, 0, text.Length);
            string message = string.Empty;
            if (!string.IsNullOrEmpty(message))
            {
                message = string.Empty;
            }
            for (int i = 0; i < length; i++)
            {
                bBytes[i] = bytes[i * 2] * 256 + bytes[i * 2 + 1];
            }
            message = System.Text.Encoding.Default.GetString
            (bBytes,0,bBytes .Length );
            return message;
        }



在给bBytes[i]赋值的时候,报“无法将int类型转化为byte”,结果应该是中文,但是bytes[i * 2] * 256 + bytes[i * 2 + 1];的结果却是int类型,所以请教大虾们如何转换该段代码呢?只要能转化正确,我立马给分结贴。
C++ C# 转换 类型

------解决方案--------------------

string DecodeUCS2(byte[] text, int length)
{
  return Encoding.BigEndianUnicode.GetString(text, 0, length);
}

------解决方案--------------------
string DecodeUCS2(byte[] text, int charCount)
{
  return Encoding.BigEndianUnicode.GetString(text, 0, charCount * 2);
}
------解决方案--------------------
bBytes换成char看看,C# char是两字节
------解决方案--------------------
        //
        // 摘要:
        //     返回由字节数组中指定位置的两个字节转换来的 Unicode 字符。
        //