将字符串转换为字符串[],然后将字符串[]转换为字节[] [英] Convert string to string[] and then convert string[] to byte[]

查看:139
本文介绍了将字符串转换为字符串[],然后将字符串[]转换为字节[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关应用程序的详细信息:

Details about the application:


  • 在Visual Studio 2019(Windows 10)下开发

  • UWP 平台上使用 C#& XAML 语言

  • Developed under Visual Studio 2019 (Windows 10)
  • Designed on UWP platform with C# & XAML language

应用程序从远程服务器接收信息。双方之间的通信使用带有套接字的连接。

The application receives information from a remote server. A connection with sockets is used for communication between the two parties.

要与服务器通信,应用程序必须将数据发送到字节数组中以便可以读取

To communicate with the server, the application must send the data in a Byte Array so that it can be read correctly.

当前,我使用此方法以字节为单位传递变量[]:

Currently I use this method to pass my variables in bytes[]:

var ID_MESSAGE_ARRAY = BitConverter.GetBytes((int)MESSAGE);
var WAY_ARRAY = BitConverter.GetBytes((int)WAY);
var SIZE_ARRAY = BitConverter.GetBytes((int)SIZE);
var TYPE_STATE_DEVICE_ARRAY = BitConverter.GetBytes((int)TYPE_STATE_DEVICE.LOGIN);

var HexString = ID_MESSAGE_ARRAY.Concat(WAY_ARRAY).Concat(SIZE_ARRAY).Concat(TYPE_STATE_DEVICE_ARRAY).Concat(ABO).ToArray();

由于收到此消息,我必须发送字符串。因此,我使用此方法将字符串编码为 bytes []

As a result of this message, I have to send a string. So I use this method to code my string into bytes[] :

string ABONNE = "TEST";
var ABO = Encoding.ASCII.GetBytes(ABONNE);

但是我有一个问题,这个 string 必须在32个字节上,而当我在另一边解码(hexa)时,我会发现:

But I have a problem, this string must be on 32 bytes, whereas when I decode (hexa) on the other side I find this:

获得的结果: 54-45-53 -54

预期结果: 54-45-53-54-00-00-00-00-00 -00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00

要找到此结果,如何在中传递我的字符串ABONNE 字符串[32] ,然后在 bytes []

To find this result, how can I pass my string ABONNE in string[32] and then in bytes[]?

推荐答案

如果直接将字符串传递到32个字节的数组,怎么办:

How about if you pass your string to 32 bytes array directly:

string ABONNE = "TEST";
Byte[] ABO = new byte[32];
Encoding.ASCII.GetBytes(ABONNE,0,ABONNE.Length,ABO,0);

两个零都是0索引(起始位置)。我还创建了一个32字节的空数组,然后用 ABONNE 中的字节填充它。 请注意,如果 Encoding.ASCII.GetBytes(ABONNE).Length 大于32个字节,则会出现异常

Both zeros are for 0-index (start position). Also I have created a 32 bytes array empty, than then it is filled with the bytes from ABONNE. Please be carefull that if Encoding.ASCII.GetBytes(ABONNE).Length is greather than 32 bytes, you will get an exception

这篇关于将字符串转换为字符串[],然后将字符串[]转换为字节[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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