简体   繁体   中英

C# convert byte to hex after mode 100 and send it using serial

I need to run mode 0x100 and send hex message

this is the mode100 function I have created (which is working )

public static byte Mode100(byte[] p)
    {
        byte lcs = 0;
        foreach (byte b in p)
        {
            lcs += b;

        }


        return lcs;

    }

this is what I'm trying to send

            byte[] msg = { 0X06, 0XA2, 0XD2, 0X06, 0XD3, 0X11, 0XD4, 0X65, 0X6F };

            var Mode100Dec = Mode100(msg);//value in int 
            string Mode100hex = Mode100Dec.ToString("X"); //value in hex 0-F 
            byte [] Mode100Byte = Encoding.Default.GetBytes(Mode100hex);//value in dec ascci of hex  
            var hexString = BitConverter.ToString(Mode100Byte); //value in hex of ascii 

for this example the the Mode100 function return me 12(Dec) which is C(Hex)

but how do I convert it to byte[] so I can send 0x0C ?

because now it change me the "C" to 67 Dec \\ 42 Hex which is wrong .....


I have look this post

How do you convert a byte array to a hexadecimal string, and vice versa?

but it didn't help me to get the answer I need

I agree with note from @500-InternalServerError that it seems you want the BINARY value, not the hex. Your example actually shows this -- your checksum would be 0x09, which is what you send. The ASCII for for 0x09 would be two characters, '0' & '9', which in ASCII would be 0x30 0x39. So I think you are confusing "Decimal" and "Hex" (which are conversion of binary values to strings) with the binary value (which is neither decimal nor hex).

To get the result you seem to be looking for, remove the conversion to a HEX string:

byte[] msg = { 0X06, 0XA2, 0XD2, 0X06, 0XD3, 0X11, 0XD4, 0X65, 0X6F };

var Mode100val = Mode100(msg);  //value as a BYTE
byte [] Mode100Byte = new byte[] { Mode100val}; 

The array of a single byte will contain a single binary value 12 decimal / 0C hex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM