项目中遇到解析PLC点位数据,欧姆龙NJ系列字符串数据存放在short数组中,是字节流形式,因此需要在代码中进行转换,废话不多说上代码
// 13143 52,0,0 字节流 数组转换 字符串
short[] bytes = new short[]{ 13143,52,0,0 } ;
byte[] byteArray = new byte[bytes.Length*2];
for (int i = 0, j = 0; i < bytes.Length; i++, j += 2) {
byteArray[j] = (byte)(bytes[i] & 0xFF);
byteArray[j + 1] = (byte)((bytes[i] >> 8) & 0xFF);
}
var str = System.Text.Encoding.ASCII.GetString (byteArray)
;
Console.WriteLine(str);
数组13143,52,0,0 ,实际转换结果是 W34.