【问题标题】:Bash script, parsing binary number from obase to string?Bash脚本,将二进制数从obase解析为字符串?
【发布时间】:2013-03-07 19:07:27
【问题描述】:

我正在编写一个执行子网计算的脚本。到目前为止,它看起来像这样(部分):

echo "Subnet Address  : "$sn1.$sn2.$sn3.$sn4
echo "BCast Address   : "$br1.$br2.$br3.$br4
echo -e "\nSubnet address in binary" :
echo "obase=2;$ip1"+"obase=2;$ip2"+"obase=2;$ip3"+"obase=2;$ip4" \
  | bc | awk '{printf("%08d",$ip1)}'
echo -e "\nBroadcast address in binary" :
echo "obase=2;$br1"+"obase=2;$br2"+"obase=2;$br3"+"obase=2;$br4" \
  | bc | awk '{printf("%08d",$br1)}'

这给了我这个输出:

Subnet address in binary :
11000010101010100000001100000000
Broadcast address in binary :
11000010101010100000001100011111
  1. 我尝试使用'{printf("%08d.",$br1)}''{printf(".%08d",$br1)}' 来分隔八位位组,但我在开头或结尾处得到了一个额外的点。
  2. 我想计算网络掩码有多少个 ace,但我真的找不到将 echo "obase=2;$br1"+"obase=2;$br2"+"obase=2;$br3"+"obase=2;$br4"| bc | awk 的输出转换为字符串的方法,因此我可以计算它们。

有什么建议吗?

【问题讨论】:

  • 这个例子并不完整,所以很难说清楚这里发生了什么。

标签: bash awk subnet bc


【解决方案1】:

所以您希望输出格式为:01111111.00000000.00000000.00000001?

嗯,我用头撞这个时使用的作弊方法是环绕 ipcalc:

%ipcalc 127.0.0.1
Address:   127.0.0.1            01111111.00000000.00000000. 00000001
Netmask:   255.255.255.0 = 24   11111111.11111111.11111111. 00000000
Wildcard:  0.0.0.255            00000000.00000000.00000000. 11111111
=>
Network:   127.0.0.0/24         01111111.00000000.00000000. 00000000
HostMin:   127.0.0.1            01111111.00000000.00000000. 00000001
HostMax:   127.0.0.254          01111111.00000000.00000000. 11111110
Broadcast: 127.0.0.255          01111111.00000000.00000000. 11111111
Hosts/Net: 254                   Class A, Loopback

然后提取我需要的东西。运行速度比通过“bc”多次解析快得多。即,如果不需要,重新发明轮子是没有意义的。

如果您确实想重新发明轮子:

$ echo "obase=2;200" + "obase=2;150" + "obase=2;200" + "obase=2;150" | \
   bc | awk '{printf "%08d\." ,$1}' | \
   sed -e 's/[.]*$//'
11001010.10011000.11001010.10010110

这将为您提供所需的 8 位二进制输出格式。

【讨论】:

  • 注意,为避免在末尾出现点,您需要在 awk 中进行一些跟踪。
【解决方案2】:

为了分隔八位位组,我会改用 printfpaste,例如:

ip1=127; ip2=0; ip3=0; ip4=1
printf "%08d\n" $(bc <<<"obase=2; $ip1; $ip2; $ip3; $ip4") | paste -sd.

或者如果ip在一个变量中:

ip=127.0.0.1
printf "%08d\n" $(bc <<<"obase=2; ${ip//./;}") | paste -sd.

输出:

00001010.00101010.01100110.11111100

要计算网络掩码中 1 的数量,只需添加它们:

netmask=255.255.255.252
printf "%08d" $(bc <<<"obase=2; ${netmask//./;}") | grep -o . | paste -sd+ | bc

输出:

30

【讨论】:

    【解决方案3】:

    两个快速解决方案:

    $ echo $br1.$br2.$br3.$br4 |  
        perl -F\\\. -anE 'say join ".", map { sprintf "%08b", $_ } @F'
    $ perl -e 'printf( "%08b.%08b.%08b.%08b\n", '$br1,$br2,$br3,$br4')'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多