1. 文本框读取byte,ushort格式数据
byte addr;
if (byte.TryParse(textBoxAddr.Text, out addr) == true)
{
}
2. 字节数组 (byte[]) 转换为 ASCII 字符串
byte[] bytes = { 72, 101, 108, 108, 111 }; // "Hello" 的 ASCII 码
string s0 = Encoding.ASCII.GetString(bytes , 0, 5);
若字节值超出 ASCII 范围(0-127),会替换为默认字符(如 ?)
3. 若字节数组中包含非 ASCII 字符(如中文),需先转换编码格式(如 UTF-8)再解码
byte[] mixedBytes = Encoding.UTF8.GetBytes("Hello 世界");
string decodedString = Encoding.UTF8.GetString(mixedBytes); // 正确解码中文
4. 十六进制字符串与 ASCII 的互转
将十六进制字符串(如 “48656C6C6F”)转为 ASCII 字符串
string hex = "48656C6C6F"; // "Hello" 的十六进制
byte[] hexBytes = Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
string result = Encoding.ASCII.GetString(hexBytes); // 输出: Hello
此方法常用于网络通信或二进制数据处理
5. string 转bytes
// UTF-8编码(汉字占3字节)
byte[] utf8Bytes = Encoding.UTF8.GetBytes("示例字符串");
// ASCII编码(仅支持英文字符,汉字会丢失)
byte[] asciiBytes = Encoding.ASCII.GetBytes("example");
// GB2312编码(汉字占2字节)
byte[] gb2312Bytes = Encoding.GetEncoding("gb2312").GetBytes("中文测试");