3

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
Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
Roger
  • 75
  • 4
  • Several literals show more than 7+1 "significant bits" - are the literals *byte* values? What do the `[Values] to verify the code` mean can you explain `#3 { 0x1, 0x0} -> 111127`? – greybeard Jan 11 '19 at 04:10
  • 2
    I think it would be more helpful if you put the full request you're making and the full response, in bytes, to your command. These seem to be just the coil outputs, and if they're wrong you'll be causing a lot of confusion. Also, are you certain you have the byte and word order correct for your particular device? – Caius Jard Jan 11 '19 at 05:47
  • https://en.wikipedia.org/wiki/Endianness ? – greenoldman Jan 11 '19 at 06:59
  • meter panel shows the number 79605 when i get the bytes { 0x1, 0x98bb } from my program via modbus protocol . The modbus function code is 3 : input register. these four number , means 4 meters , to verify the parser works or not. – Roger Jan 11 '19 at 13:59

0 Answers0