AWK将十进制转换为二进制

时间:2019-03-19 11:03:51

标签: awk binary decimal

我想使用AWK将文件中的十进制数字列表转换为二进制,但是似乎没有内置方法。示例文件如下:

134218506
134218250
134217984
1610612736
16384
33554432

5 个答案:

答案 0 :(得分:1)

您可以尝试Perl单线版

$ cat hamdani.txt
134218506
134218250
134217984
134217984
1610612736
16384
33554432


$  perl -nle ' printf("%b\n",$_) ' hamdani.txt
1000000000000000001100001010
1000000000000000001000001010
1000000000000000000100000000
1000000000000000000100000000
1100000000000000000000000000000
100000000000000
10000000000000000000000000

$

答案 1 :(得分:1)

这是一种令人敬畏的方式,为您带来愉悦的功能:

awk '
function d2b(d,  b) {
      while(d) {
          b=d%2b
          d=int(d/2)
      }
      return(b)
}
{
    print d2b($0)
}' file

前三个记录的输出:

1000000000000000001100001010
1000000000000000001000001010
1000000000000000000100000000

答案 2 :(得分:1)

您可以尝试使用dc:

# -f infile : Use infile for data
# after -e , it is there are the dc command
dc -f infile -e '
  z          # number of values
  sa         # keep in register a
  2
  o          # set the output radix to 2 : binary
  [
    Sb       # keep all the value of infile in the register b  
             # ( b is use here as a stack)
    z
    0 <M     # until there is no more value
  ] sM       # define macro M in [ and ]
  lMx        # execute macro M to populate stack b
  [ 
    Lb       # get all values one at a time from stack b
    p        # print this value in binary
    la       # get the number of value
    1
    -        # decremente it
    d        # duplicate
    sa       # keep one in register a
    0<N      # the other is use here
  ]sN        # define macro N
  lNx'       # execute macro N to print each values in binary

答案 3 :(得分:1)

这是一种首先将十进制转换为十六进制,然后将每个十六进制字符转换为其等效二进制的方法:

$ cat dec2bin.awk
BEGIN {
    h2b["0"] = "0000";  h2b["8"] = "1000"
    h2b["1"] = "0001";  h2b["9"] = "1001"
    h2b["2"] = "0010";  h2b["a"] = "1010"
    h2b["3"] = "0011";  h2b["b"] = "1011"
    h2b["4"] = "0100";  h2b["c"] = "1100"
    h2b["5"] = "0101";  h2b["d"] = "1101"
    h2b["6"] = "0110";  h2b["e"] = "1110"
    h2b["7"] = "0111";  h2b["f"] = "1111"
}

{ print dec2bin($0) }

function hex2bin(hex,   n,i,bin) {
    n = length(hex)
    for (i=1; i<=n; i++) {
        bin = bin h2b[substr(hex,i,1)]
    }
    sub(/^0+/,"",bin)
    return bin
}

function dec2bin(dec,   hex, bin) {
    hex = sprintf("%x\n", dec)
    bin = hex2bin(hex)
    return bin
}

$ awk -f dec2bin.awk file
1000000000000000001100001010
1000000000000000001000001010
1000000000000000000100000000
1100000000000000000000000000000
100000000000000
10000000000000000000000000

答案 4 :(得分:0)

您不应为此使用@ECHO OFF set IPADDRESS=www.google.com set INTERVAL=10 :PINGINTERVAL ping %IPADDRESS% -n 1 timeout %INTERVAL% GOTO PINGINTERVAL ,而应使用awk

bc

$ bc <<EOF
  ibase=10
  obase=2
  $(cat file)
  EOF