在C#中将字符串转换为等效字节的十六进制 [英] Converting string to equivalent byte hex in c#

查看:125
本文介绍了在C#中将字符串转换为等效字节的十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字符串 68016101061B4A60193390662046804020422044204000420040402060226024676DB16 并且我想转换为 0x68 0x01 0x61 0x01 0x06 0x1B 0x4A 0x60 0x0B 0x86 0xE8 0x46 0x04 0x0 00 004 0x04 0x04 0x0 0x0 0x0 0x0 0x0x 0x0x 0x0x 0x0x 0x0x 0x000x40 0x02 0x06 0x02,0x26 0x02 0x46 0x76 0xDB 0x16 ,但以字节为单位.我想将这些字节写入串行端口.

I have an incoming string 68016101061B4A60193390662046804020422044204000420040402060226024676DB16 and I want to convert into 0x68 0x01 0x61 0x01 0x06 0x1B 0x4A 0x60 0x0B 0x86 0xE8 0x46 0x04 0x68 0x04 0x02 0x04 0x22 0x04 0x42 0x04 0x00 0x04 0x20 0x04 0x40 0x02 0x06 0x02, 0x26 0x02 0x46 0x76 0xDB 0x16 but in bytes. I want to write these bytes into a serial port.

port.Write(bytes,0,bytes.Length);

更新1

下面是我通过硬编码发送的字节数组

Below is the byte array that I am sending by hard coding it

var dataItems = new byte[] { 0x68, 0x01, 0x61, 0x01, 0x06, 0x1B, 0x4A, 0x60, 0x0B, 0x86, 0xE8, 0x46, 0x04, 0x68, 0x04, 0x02,
            0x04, 0x22, 0x04, 0x42, 0x04, 0x00, 0x04, 0x20, 0x04, 0x40, 0x02, 0x06, 0x02, 0x26, 0x02, 0x46 ,0x76 ,0xDB ,0x16 };

它在数组下面给了我

如何转换?

推荐答案

您可以使用正则表达式来做到这一点:

You can use a regular expression to do this:

var regex = new Regex(@"(\d{2})");

string aString = "040204220442040004200404020602260246";
string replaced = regex.Replace(aString, "x$1 ");

小提琴

编辑似乎您需要字节而不是字符串,可以使用此处建议的基于Linq的答案之一或简单的循环:

EDIT It seems like you need bytes instead of a string, you can use one of the Linq based answers suggested here or a simple loop:

if ((aString.Length % 2) != 0)
{
    // Handle invalid input
}

var bytes = new byte[aString.Length / 2];

int index = 0;
for (int i = 0; i < aString.Length; i += 2)
{
    string digits = aString.Substring(i, 2);
    byte aByte = (byte)int.Parse(digits, NumberStyles.HexNumber);

    bytes[index++] = aByte;
}

port.Write(bytes, 0, bytes.Length);

请注意,如果GC压力成为问题,则可以使用 ReadOnlySpan< char> .

Note that if GC pressure became an issue, you could use ReadOnlySpan<char>.

小提琴

这篇关于在C#中将字符串转换为等效字节的十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆