C#16进制数转为10进制有符号数——处理传感器16进制字节流原始数据

原数据是四个字节组成例如 B102 一共16bit,要转化成有符号数,则最大是2^15,范围是(-32768,32768).

转换公式:

1.先转化为10进制trans

int xx= Convert.ToInt32(x, 16);

2.判断是否超了最大值

 xx < Math.Pow(2, 15) ? xx :  Math.Pow(2, 15)-xx

传感器响应数据从16原始字节流数据

例如:

发送:55 55 01 32 AA AA

返回:55 55 01 32 01 AB B1 02 03 05 32 14 AA AA

0X 01AB=427; 0X B102=-12546; 0X 0305=773; 0X 3214=12820 xxxx yyyy zzzz tttt 分别组成 16 位数,最高位为符号位,1 为负,0 位正

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace psdProcess
{
    public class psdProcess
    {
        //将字节流转化为16进制字符串
        public static List<string> BytesToStringHex(byte[] bytes)
        {
            List<string> result = new List<string>();
            for (int i = 0; i < bytes.Length; ++i)
            {
                result.Add (bytes[i].ToString("X2"));
            }
            return result;
        }
        public static double[] getValues(List<string> input)
        {
            double[] result = new double[2] { 500.00, 500.00 };
            if (input.Count == 14 && input[0]=="55"&& input[1] == "55"&& input[12] == "AA"&& input[13] == "AA")
            {
                string x = input[4] + input[5];
                string y = input[6] + input[7];
                int xx= Convert.ToInt32(x, 16);
                int yy = Convert.ToInt32(y, 16);
                result[0] = xx < Math.Pow(2, 15) ? xx :  Math.Pow(2, 15)-xx;
                result[1] = yy < Math.Pow(2, 15) ? yy :  Math.Pow(2, 15)-yy;
            }
            return result;
        }
        //测试用将输入的测试字符串数组例如55 55 01 32 01 AB B1 02 03 05 32 14 AA AA拆分成list<string>
        public static List<string>getInputStringList(string temp)
        {
            List<string> list = new List<string>();
            int l = 0;
            while (l < temp.Count())
            {
                string cur = "";
                if (temp[l] != ' ')
                {
                    while (l < temp.Length && temp[l] != ' ') { cur += temp[l]; ++l; }
                    list.Add(cur);
                }
                else
                {
                    while (l < temp.Length && temp[l] == ' ') ++l;
                }
            }
            return list;
        }
    }
    
}

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值