C#将字符串转换成short数组,用于回写PLC寄存器

PLC寄存器中有的字符串是以short数组形式存放的,作为上位软件需要读取并解析,会涉及到字符串转数组,数组转回字符串的情况,代码如下:

public static string HandleCodeString(short[] bytes)
        {
            try
            {
                // 13143 52  字节流 数组转换 字符串
                //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);
                return str.Replace("\n", "").Replace("\r", "").Replace("\0", "");
            }
            catch
            {
                return "";
            }
        }


        public static short[] StringToByteArray(string input)
        {
            // 将输入字符串转换为字节数组
            byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(input);

            // 创建一个新的 short 数组,长度等于字节数组的长度除以2,向上取整
            short[] result = new short[(byteArray.Length + 1) / 2];

            // 将字节数组中每两个连续的字节转换为一个 short
            for (int i = 0; i < byteArray.Length; i += 2)
            {
                if (i + 1 < byteArray.Length)
                {
                    result[i / 2] = (short)((byteArray[i + 1] << 8) | byteArray[i]);
                }
                else
                {
                    result[i / 2] = byteArray[i];
                }
            }

            return result;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

11eleven

你的鼓励是我创作的动力 !

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值