Convert string to string[] and then convert string[] to byte[]

纵饮孤独 提交于 2019-12-13 18:45:47

问题


Details about the application:

  • 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();

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);

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

Obtained result : 54-45-53-54

Expected result : 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

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


回答1:


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);

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




回答2:


Use StringBuilder to pad your string with a necessary number of nulls.

StringBuilder sb = new StringBuilder(ABONNE);
sb.Append((char)0,32-ABONNE.Length);

Updated a working example instead of a pseudo-code.



来源:https://stackoverflow.com/questions/56288583/convert-string-to-string-and-then-convert-string-to-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!