1

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 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

7 Comments

Was writing the same: here is MSDN on this particular overload
var ABO returns an int and not a byte[]
@ValentinDubois-Pivot I have changed the variables names using yours
@val , Some GetBytes return byte[] but if you pass in parameter the byte pointer or bytes array they have to write on they return int the number of byte wrote.
@xdtTransform Thanks for the help, @ ganchito55 to change his answer and it works perfectly
|
-1

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 Comments

The 0 will result in a hexa code of 30, right so the array wiil be padded with 30 30 30 insteand of 00 00 00
@xdtTransform That's not a character '0' it's character \0.
confusion was born from the pseudo code as there where no overload that took int like this. I was left with it's either 0 or (char)0.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.