如何在bash中执行二进制加法 [英] How to do binary addition in bash

查看:88
本文介绍了如何在bash中执行二进制加法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加两个32位二进制数.其中一个是常数( address_range_in_binary ),另一个是常数( IPinEachSubnet [$ val] )

I am trying to add two 32 bit binary numbers. One of them is a constant (address_range_in_binary) , and another one is an element of an array (IPinEachSubnet[$val])

我正在尝试遵循

I am trying to follow the instructions here, but I could not figure out how to get it done using variables. I have been trying to use different combinations of the below, but none of them seems to work. It is probably a simple syntax issue. Any help would be appreciated. The following is printing some negative random values.

例如,如果值如下:

$address_range_in_binary=00001010001101110000101001000000
$IPinEachSubnet[$val]=00000000000000000000000000010000

echo "ibase=2;obase=2;$((address_range_in_binary+IPinEachSubnet[$val]))" | bc -l

此输出为 -1011101110111111110

推荐答案

让我们定义您的变量(我将使用较短的名称):

Let's define your variables (I will use shorter names):

$ y=00001010001101110000101001000000
$ t=00000000000000000000000000010000

现在,让我们运行有问题的命令:

Now, let's run the command in question:

$ echo "ibase=2;obase=2;$((y+t))" | bc -l
-1011101110111111111

以上内容会产生您观察到的错误结果.

The above produces that incorrect result that you observed.

要获得正确的结果:

$ echo "ibase=2;obase=2; $y+$t" | bc -l
1010001101110000101001010000

讨论

命令 $((y + t))告诉bash假设数字以10为底进行加法.bash添加的结果将传递到 bc .这不是您想要的:您希望 bc 进行添加.

Discussion

The command $((y+t)) tells bash to do the addition assuming that the numbers are base-10. The result of bash's addition is passed to bc. This is not what you want: You want bc to do the addition.

$ y=00001010001101110000101001000000
$ arr=(00000000000000000000000000010000)
$ echo "ibase=2;obase=2; $y+${arr[0]}" | bc -l
1010001101110000101001010000

这篇关于如何在bash中执行二进制加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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