将字符串转换为十六进制并在TCP端口上发送 - C# [英] Convert string to hex and send on TCP port - C#

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

问题描述

大家好



如何发送此信息包?

{68} {31} { 39} {33} {32} {32} {37} {16}



我的尝试:



hi everyone

How can I send this packet?
{68}{31}{39}{33}{32}{32}{37}{16}

What I have tried:

string serialnumber = "193227";
byte[] k = Encoding.Default.GetBytes(serialnumber);
var hexString = BitConverter.ToString(k); //My string converted to hex: {31}{39}{33}{32}{32}{37}

byte start = 0x68;
int middle = hexString;
byte end = 0x16;
byte[] packet = new byte[] { start, middle, end };

ns.Write(packet, 0, packet.Length);





最终我想发送:{68} {31} {39} {33} {32} {32} {37} {16}

感谢您的帮助



Finaly I want to send: {68}{31}{39}{33}{32}{32}{37}{16}
thanks for help

推荐答案

这不太可能像你想要的那样 - 因为 BitConverter.ToString方法(字节[])(系统) [ ^ ]将一个字节值数组转换为十六进制数字字符串,用连字符分隔:

That is unlikely to be anything like what you want - because the BitConverter.ToString Method (Byte[]) (System)[^] mocverts an array of byte values to a string of hex digits, separated by hyphens:
00-01-02-04-08-10-20-40-80

而且很多,很可能你的目的地需要原始十六进制值 - 你已经在字节数组中。

试试这个:

And it's a lot, lot more likely that you destination needs the raw hex values - which you already have inside the byte array.
Try this:

private const byte start = 0x68;
private const byte end = 0x16;
private byte[] Enpack(byte[] data)
    {
    int packetLength = 1 + data.Length + 1;
    byte[] packet = new byte[packetLength];
    packet[0] = start;
    packet[packetLength - 1] = end;
    Array.Copy(data, 0, packet, 1, packetLength - 2);
    return packet;
    }



您可能想要使用特定集替换默认编码:Ascii或UTF8,具体取决于目的地。


And you might want to replace the Default encoding with a specific set: Ascii perhaps, or UTF8 depending on the destination.


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

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