Converting Two's Complement in groovy

I have a number of devices that I maintain drivers for that take negative values for the parameter. As expected, they are in two's complement in terms of notation.

I normally just brute force it in a quick function (value == -1 ? 255 : value == -2 ? 254) etc.

But I thought I would try to learn something for once and see if there was a more elegant way to do this. So, is there a quick way to convert a signed integer to its two's complement resultant value?

How about something like

def x = -1
value = 256 - Math.abs(x)

Math.abs() will turn a negative number into a positive and keep a positive a positive.

I'm not sure if you would need to put another check in to only do it if x is < 0.

Yeah, that would be easier than how I'm doing it now...

if (val<0) {newVal = 256 + val}

Or subtracting the abs like you did. Same thing.

1 Like

Another way is this:
before you turn the binary string into a decimal take a look at the MSB to see if it is a '1' or '0' -
if MSB is a '1' then turn it into a '0' (or remove it from the string), convert to a decimal and multiply the decimal result by -1.0,
else if MSB was '0' just convert to a decimal

Here is how I do it in Python (you can convert it to groovy):

def bin2s2dec(numStr):
  bitMSB = numStr[0:1]
  if bitMSB == '1':
    return -1 * int(numStr[1:],2)
    return int(numStr, 2)
1 Like