0

I guess its very simple but it wasted my time a lot but still no luck!

the following is working very nicely-

sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] bytes=new byte[]{0x7F, 0x00, 0x00, 0x21, 0x09, 0x7F, 0x30, 0x00, 0x15, 0x02, 0x02, 0x00, 0xEE, 0x28, 0xCB, 0x87 };
sck.Connect("192.168.1.100", 8008);
sck.Send(bytes);
sck.Close();

and, if I keep those array of hex strings in a text box like-

textbox1.Text="0x7F, 0x00, 0x00, 0x21, 0x09, 0x7F, 0x30, 0x00, 0x15, 0x02, 0x02, 0x00, 0xEE, 0x28, 0xCB, 0x87";

But, I need to use the textbox1.Text string for the same task; like-

sck.Send(textbox1.Text);

I tried a lot but could not come up with any solution. Please guide me...

In fact, I'll keep the hex string in the database as string and will be retrieved later in my program.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73

2 Answers2

0

Firstly, the difference between a string and a byte array is :

"0x03" as a string is of 4 bytes
 0x03 as an entry in a byte array is of 1 byte

So what you need to do is Delimit the string at , and separate different hexadecimal strings, store them in a string array or any other data structure.

Then you have to convert these strings to a single byte using some function or you can create your own method, one of them can be found here.

Store these bytes in a byte array and you're good to go.

Community
  • 1
  • 1
NoSuchUserException
  • 700
  • 1
  • 9
  • 18
0

I did it the following way:

txtHexString.Text="0x11, 0x01, 0x49, 0x4D, 0x41, 0x47, 0x45, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x53, 0x75, 0x6D, 0x6D, 0x61, 0x72, 0x79, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00";

string[] namesArray =  txtHexString.Text.Split(',');
byte[] abc= new byte [namesArray.Length];

for (int i = 0; i <= namesArray.Length - 1; i = i + 1)
        {
            abc[i] = Convert.ToByte(namesArray[i].Replace(" ", ""), 16);
        }

here, abc is the desired byte array.