我有一个字符串,我想发送它作为十六进制值而不是ascii值
我的字符串是:
0x5C 0x21 0x5C
但是当我发送它时,我发送:
30-78-35-43-20-30-78-32-31-20-30-78-35-43
我怎么能过来这个?
我错过了什么?
这是完整的代码:
byte[] address = { 0x30, 0x35 };
byte[] end = { 0x03 };
string Start = "0x5C 0x21 0x5C 0x73 0x20 0x73";
for (int x = 0; x < msg.Count; x++)
Console.WriteLine(Start);
byte[] ByteMessage = encoding.GetBytes(Start);
string HexMessage = BitConverter.ToString(ByteMessage);
var temp = new MemoryStream();
temp.Write(address, 0, address.Length);
temp.Write(ByteMessage, 0, ByteMessage.Length);
temp.Write(end, 0, end.Length);
byte[] testing = temp.ToArray();
var lrs = gen(testing);
string lrsString = lrs.ToString("X");
Console.WriteLine("MSG in HEX - " + HexMessage);
Console.Write(
Encoding.Default.GetString(address) +
encoding.GetString(ByteMessage) +
Encoding.Default.GetString(end) +
);
byte[] LRS = Encoding.Default.GetBytes(lrsString);
try
{
sp1.Write(start, 0, start.Length); //send start
sp1.Write(testing, 0, testing.Length);//send the all msg
sp1.Write(LRS, 0, LRS.Length);//send the Check Sum
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
}
谢谢 ,
您可能正在寻找解析(每个string
项目,如"0x5C"
应解析为相应的byte
:0x5C
):
string Start = "0x5C 0x21 0x5C";
byte[] ByteMessage = Start
.Split(' ') // Split string into items
.Select(item => Convert.ToByte(item, 16)) // Parse items into corresponding bytes
.ToArray(); // Materialize into array
// Back to Hex (let's have a look on what we are going to send): "5C-21-5C"
string HexMessage = string.Join("-", ByteMessage
.Select(item => item.ToString("X2")));