举例BASH二的六角值的补充? [英] Example for BASH two's complement with Hex values?

查看:91
本文介绍了举例BASH二的六角值的补充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个收集通过SNMP十六进制值的例程。下面是从我的bash脚本08 01 18 00 FF FF真正的集合。该值是$ expr的底座((16#$ {数组[4]})) - $((16#$ {数组[5]})),这样的结果是0,我怎么介绍二是补充? expr的$的正确值((16#$ {数组[4]})) - $((16#$ {数组[5]}))-1是基于我的工作的例子

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.

推荐答案

为了方便起见,让我们创建一个bash函数:

For convenience, let's create a bash function:

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

现在

$ 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 ""; }

使用范例:

$ twosx 00 01 7F 80 FE FF
0 1 127 -128 -2 -1 

这篇关于举例BASH二的六角值的补充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆