Unity 十六进制字符串转Byte

    private byte[] Convert16(string strText)
    {
        strText = strText.Replace(" ", "");
        byte[] bText = new byte[strText.Length / 2];
        for (int i = 0; i < strText.Length / 2; i++)
        {
            bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
        }
        return bText;
    }

 

Unity中处理十六进制串口数据通常涉及到两个步骤:首先,你需要接收来自外部设备(如蓝牙、串口模块等)的数据,然后将这些十六进制字符串换为可以操作的二进制数据。 1. **接收十六进制数据**:Unity本身并不直接支持串口通信,但你可以通过第三方插件如`UnityEngine.Experimental.IO.Compression.Streams`或利用C#的System.IO.Ports命名空间下的SerialPort类来进行串口连接。编写一个委托函数或者使用事件系统,当接收到新的串口数据时,将其解析成十六进制字符串。 ```csharp using System.IO.Ports; // ... private SerialPort serialPort; private void Start() { serialPort = new SerialPort("COM1", 9600); // 设定端口号和波特率 serialPort.DataReceived += SerialPort_DataReceived; // 注册数据接收事件 } private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { string hexData = serialPort.ReadExisting().ToString("X"); // 将读取的字节十六进制字符串 ProcessHexData(hexData); } ``` 2. **处理十六进制数据**:`ProcessHexData`函数会解析十六进制字符串换为二进制,如果需要的话,还可以进一步按需解码成特定的数据结构(比如字节数组)。 ```csharp private byte[] HexToBytes(string hex) { int len = hex.Length / 2; byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); } return bytes; } void ProcessHexData(string hexData) { byte[] data = HexToBytes(hexData); // 这里可以对data进行进一步的操作... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值