简体   繁体   English

等价于.Net 2.0中的Convert.ToChar(byte)?

[英]Equivalent of Convert.ToChar(byte) in .Net 2.0?

I'm confined to using only .Net 2.0 and trying to write something that will convert a byte to char. 我仅限于使用.Net 2.0并尝试编写一些将字节转换为char的东西。

Ideally I would use Convert.ToChar(buffer[i]); 理想情况下,我将使用Convert.ToChar(buffer[i]); to get a char from a byte in a byte[] array but in .Net 2.0 this feature didn't exist. byte[]数组中的byte中获取字符,但是在.Net 2.0中,此功能不存在。 Using BitConverter.ToChar(buffer, i) seems to always result in array out of bounds errors. 使用BitConverter.ToChar(buffer, i)似乎总是导致数组超出范围错误。

Does anyone have a suggestion on how I might convert a byte to char in .Net 2.0? 有没有人建议我如何在.Net 2.0中将字节转换为char?

If you just have a byte then you have to assume the character is ASCII. 如果只有一个byte则必须假定字符为ASCII。 char is Unicode 16. The 1st 128 code values of ASCII map directly to Unicode. char是Unicode16。ASCII的第1 128个代码值直接映射到Unicode。 So try this 所以试试这个

public char ToChar(byte b)
{
  if (b < 0 || b > 127)
     throw new ArgumentException("Not an ASCII character.");
  return (char) b;
}

UPDATE 更新

Most network software now assumes a string is encoded in UTF-8. 现在,大多数网络软件都假定字符串以UTF-8编码。 So if you know the number of bytes in the buffer then you should do 因此,如果您知道缓冲区中的字节数,则应该

var s = Encoding.Utf8.GetString(buffer, i, n);

Where n is the number of bytes. 其中n是字节数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM