Example for BASH two's complement with Hex values?

佐手、 提交于 2019-12-24 05:35:09

问题


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.


回答1:


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 


来源:https://stackoverflow.com/questions/31798565/example-for-bash-twos-complement-with-hex-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!