Convert string to string[] and then convert string

2019-07-30 16:39发布

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[]?

2条回答
冷血范
2楼-- · 2019-07-30 17:27

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.

查看更多
该账号已被封号
3楼-- · 2019-07-30 17:28

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

查看更多
登录 后发表回答