Search code examples
c#modbus

c# How to divide Byte by digits


I am developing Modbus communication module in c# programming language,

If an exception occurs in the process of communicating with the modbus protocol,

The error code is returned, which is the Hex value,

Suppose the error code format is 0x84, for example

0x80 -> Header

0x04 -> Body

It's in the same format as

So I want to divide 0x84 by 0x80 and 0x04

Is there any material I can refer to?


Solution

  • If I'm reading this question correctly, you're asking about how to perform bit-masking. You don't have hex values. Hexadecimal is simply one of many ways you can represent numbers in written form. You simply have a byte, i.e. an 8-bit number. You're asking how to separate the lower-order and higher-order 4 bits. You can do that using bit-masking. You can use a bitwise AND operation to mask out the top four or bottom four bits like so:

    byte n1 = 0x84;
    byte m1 = 0x0F;
    byte m2 = 0xF0;
    byte n2 = (byte)(n1 & m1);
    byte n3 = (byte)(n1 & m2);
    
    Console.WriteLine($"{Convert.ToString(n1, 2),8} 0x{n1:X2}");
    Console.WriteLine($"{Convert.ToString(m1, 2),8} 0x{m1:X2}");
    Console.WriteLine($"{Convert.ToString(m2, 2),8} 0x{m2:X2}");
    Console.WriteLine($"{Convert.ToString(n2, 2),8} 0x{n2:X2}");
    Console.WriteLine($"{Convert.ToString(n3, 2),8} 0x{n3:X2}");
    

    The output for that is like so:

    10000100 0x84
        1111 0x0F
    11110000 0xF0
         100 0x04
    10000000 0x80
    

    I'm not going to explain the details of how bit-masking works. It's basically just Boolean logic on bits so, if you don't understand that, you should read up on Boolean logic and then bitwise logic.

    If you actually do have a string containing "0x84" then you can simply parse that to an actual byte and then do as above:

    var s = "0x84";
    var b = Convert.ToByte(s, 16);