c# hexa conversion

Asked

Viewed 141 times

1

I need to create an array of bytes with the following content:

byte[] arr = new byte { 0x4f, 0x4e };

I happen to have the string "ON", where "O" = 4f in hexa and "N" = 4e

I have tried directly storing the hexa value in the byte array without the 0x, but when sending to the serial port that way, it doesn’t work, it has to be in the format 0x00.

How to convert string to hexadecimal array?

  • Perhaps the problem lies elsewhere.

1 answer

2

You can use the class Encoding, that has methods to convert strings to bytes. In your case, for example, you can use Encoding.ASCII:

byte[] arr = Encoding.ASCII.GetBytes("ON");
  • Carlos, I need the answer in hexa. calling this method I have it in decimal.

  • What exactly do you need? Hexadecimal or decimal is a way to represent a value. In this code snippet above, the array has 2 values, 0x4F (or 79) and 0x4E (or 78). If these are the bytes you need to send to the serial port, then you already have.

  • When I write 79 in the array and send it to the serial, it doesn’t trigger the automation, when I put 0x4f in the array, it works. I need to convert this string to the byte array, more populated in hexa format.

  • How are you sending the array to the serial port? The statements byte[] arr = new byte[] { 0x4f, 0x4e } gives you the same result as the declaration byte[] arr = Encoding.ASCII.GetBytes("ON"). The statement byte[] arr = new byte[] { 79, 78 } is also equivalent to the first.

  • Yeah, but byte sending[] arr = new byte[] { 0x4f, 0x4e } works.

  • I am using the serial port class Serialport with = new Serialport(); .... com.Write(array, 0, array.Length);

  • Take a look at the debugger before the call to com.Write(array, 0, array.Length) to look at the value of the array being written. All the alternatives I cited in my previous comment should generate the same array.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.