2

I have a routine that is collecting a hex value via SNMP. Here is a real collection from my bash script 08 01 18 00 FF FF. The value is base on expr $((16#${array[4]})) - $((16#${array[5]})) so the results are 0, how do I introduce two is complement? The correct value for expr $((16#${array[4]})) - $((16#${array[5]})) is -1 based on the example I am working on.

3
  • Can you explain why FF - FF should be -1? Commented Aug 4, 2015 at 0:06
  • FF - FF should be 0. Commented Aug 4, 2015 at 0:09
  • Unsigned value of 255 in twos complement is -1, how do you use twos complement in bash so if I had 255 how do I convert to -1 Commented Aug 4, 2015 at 0:11

1 Answer 1

2

For convenience, let's create a bash function:

twos() { x=$((16#$1)); [ "$x" -gt 127 ] && ((x=x-256)); echo "$x"; }

Now:

$ twos FF
-1
$ twos FE
-2
 $ twos 01
1

Converting multiple values in one call

Define an eXtended two's complement function:

$ twosx() { for x in "$@"; do x=$((16#$x)); [ "$x" -gt 127 ] && ((x=x-256)); printf "%s " "$x"; done; echo ""; }

Sample usage:

$ twosx 00 01 7F 80 FE FF
0 1 127 -128 -2 -1 
Sign up to request clarification or add additional context in comments.

2 Comments

is it possible to use echo for twosx() so I can combine the output with another string in the script like echo 'device 1=' twos & twosx 00 01 7F 80 FE FF
How about: echo "device 1=$(twosx 00 01 7F 80 FE FF)" ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.