ValentinDP
ValentinDP

Reputation: 323

How convert UInt and others types to String Hex to send data to a server? C#

Details about the application:

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.

I need to pass these variables to String Hex and then I have a method to pass String Hex to Byte Array.

Variables to send :

 UInt16 ID_MESSAGE = 201;
 SByte ID_WAY = -1;
 UInt16 SIZE = 16;

 enum TYPE_STATE_DEVICE
 {
    LOGOUT = 0,
    OUT_OF_ORDER,
    LOGIN,
    REPLAY
 };

How I can pass these variables in hexadecimal to find the same values ​​below?

Here are the values ​​that the variables must have in hexadecimal:

ID_MESSAGE = C9-00-00-00
ID_WAY = FF-FF-FF-FF
SIZE = 10-00-00-00
TYPE_STATE_DEVICE.LOGIN = 02-00-00-00

So the complete String Hex must be like this:

HexString = C9-00-00-00-FF-FF-FF-FF-10-00-00-00-02-00-00-00

Upvotes: 0

Views: 226

Answers (1)

wertzui
wertzui

Reputation: 5720

You can put all your values into a byte array and then use the BitConverter class to convert it into a string.

var ID_MESSAGE_ARRAY = BitConverter.GetBytes((int)ID_MESSAGE);
var ID_WAY_ARRAY = BitConverter.GetBytes((int)ID_WAY);
var SIZE_ARRAY = BitConverter.GetBytes((int)SIZE);
var TYPE_STATE_DEVICE_ARRAY = BitConverter.GetBytes((int)TYPE_STATE_DEVICE.LOGIN);

var HexString = BitConverter.ToString(ID_MESSAGE_ARRAY.Concat(ID_WAY_ARRAY).Concat(SIZE_ARRAY).Concat(TYPE_STATE_DEVICE_ARRAY).ToArray());

Upvotes: 2

Related Questions