[英]High value variable in Linux
I want to read a binary number that can be of any length from 1 to 32 digits. 我想读取一个二进制数字,该数字可以是1到32位之间的任何长度。
Example: 1, 10, 101, 10000001....10000000100000001000000010000000 示例:1、10、101、10000001 .... 10000000100000001000000010000000
Now, what I want to do is to count the place of all the occurrences of 1 and ADD them. 现在,我要做的是计算所有1的出现位置并添加它们。
Example: 10001000 (8 digits number) 示例:10001000(8位数字)
Going by binary first 1 comes in at 3rd position and second 1 comes in at 7th position. 通过二进制进行运算,第一个1进入第3位,第二个1进入第7位。
What I want is finally get the result 10 (ie 7+3) 我想要的是最终得到结果10(即7 + 3)
Sample Input: 输入样例:
10001000
100100
1000000000101
10010000001
100000001
Sample Output: 样本输出:
10
7
14
17
8
Note: Number can be upto 32 digits. 注意:最多可以输入32位数字。
My Code : 我的代码:
while read line
do
count1=0
count2=0
while [ $line -gt 0 ]
do
if (($line % 2 == 0))
then
count2=$(($count2+1))
line=$(($line/10))
else
line=$(($line/10))
count1=$(($count1+$count2))
count2=$(($count2+1))
fi
done
echo $count1
done < h2b.csv >> bit_count.csv
h2b.csv is Input file and bit_count is output file. h2b.csv是输入文件,bit_count是输出文件。
This works for smaller values like 1001,1010,1100 but fails to run large value number with more than 16 digits. 这适用于较小的值,例如1001、1010、1100,但无法运行大于16位数字的较大值。
Error Message when i run my script: 当我运行脚本时出现错误信息:
line 7: [: 1000000000000000000000: integer expression expected
With this as the sample input: 以此作为示例输入:
$ cat input
10001000
100100
1000000000101
10010000001
100000001
We can calculate the result with: 我们可以用以下方法计算结果:
$ awk -F '' '{x=0; for (i=NF;i>0;i--) if ($i) x+=NF-i; print x}' input
10
7
14
17
8
-F ''
This tells awk to treat each character as a separate field. 这告诉awk将每个字符视为一个单独的字段。
x=0
This initializes the variable x
to zero. 这会将变量
x
初始化为零。
for (i=NF;i>0;i--) if ($i) x+=NF-i
This adds up the total. 这加起来就是总数。
print x
This prints the total for this line. 这将打印此行的总数。
The line in this file is 106 characters long: 此文件中的行长为106个字符:
$ cat >input2
1000100010010010001000100000000100000100000000001000000000000110000000000001100000000000100000000110000001
$ wc input2
1 1 107 input2
$ awk -F '' '{x=0; for (i=NF;i>0;i--) if ($i) x+=NF-i; print x}' input2
1035
With the same logic: 具有相同的逻辑:
while read -r line
do
x=0
for ((i=${#line};i>0;i--))
do
[ ${line:$i-1:1} = 1 ] && ((x+=${#line}-i))
done
echo $x
done <input
This produces the output: 产生输出:
10
7
14
17
8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.