C# Parsing Bytes as 2's complement from reading modbus Device

Viewed 121

I read bytes from modbus device, and need to parse the bytes to integer. I try many ways to get the correct value, but no even close the target.

ushort[] sourceBytes = new ushort[] { 0x1, 0x98bb };//from modbus     
int target = 79605;// near this value will be ok, 'cause the value increasing    

//Try One

public static uint ushortTo2Comp(ushort H, ushort L)
{           
    uint result = BitConverter.ToUInt32(
                BitConverter.GetBytes(L).Concat(BitConverter.GetBytes(H)).ToArray(), 0);
    uint b = ~result+1;
    return b;
 }

//Try Two

public static ushort ushortTo2Comp2(ushort Hs, ushort Ls)
{
    ushort H = (ushort)(~Hs + 1);
    ushort L = (ushort)(~Ls + 1);
    return BitConverter.ToUInt16(
                BitConverter.GetBytes(H).Concat(BitConverter.GetBytes(L)).ToArray(), 0);
    }

Other values to verify the code:

 #1 { 0x1, 0x98bb } -> 79605
 #2 { 0x0, 0x1f6 } -> 39009
 #3 { 0x1, 0x0} -> 111127
 #4 { 0x1, 0xb2dd} -> 66035
0 Answers
Related