【发布时间】:2019-08-09 21:22:15
【问题描述】:
我想使用 AWK 将文件中的十进制数字列表转换为二进制,但似乎没有内置方法。示例文件如下:
134218506
134218250
134217984
1610612736
16384
33554432
【问题讨论】:
我想使用 AWK 将文件中的十进制数字列表转换为二进制,但似乎没有内置方法。示例文件如下:
134218506
134218250
134217984
1610612736
16384
33554432
【问题讨论】:
这是一种 awk 方式,为了您的乐趣而发挥作用:
awk '
function d2b(d, b) {
while(d) {
b=d%2b
d=int(d/2)
}
return(b)
}
{
print d2b($0)
}' file
前三个记录的输出:
1000000000000000001100001010
1000000000000000001000001010
1000000000000000000100000000
【讨论】:
你可以试试 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
$
【讨论】:
你可以用 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
【讨论】:
这是一种方法,首先将十进制转换为十六进制,然后将每个十六进制字符转换为等效的二进制:
$ 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
【讨论】:
您不应为此使用awk,而应使用bc:
$ bc <<EOF
ibase=10
obase=2
$(cat file)
EOF
或
bc <<< $(awk 'BEGIN{ print "ibase=10; obase=2"}1' file)
【讨论】:
awk”是不可接受的答案。