3

我正在尝试对两个大的二进制值进行异或。然而,

echo ${hashArray[1]}
echo ${hashArray[2]}
echo $((${hashArray[1]} ^ ${hashArray[2]}))

给出:

10100100000111101011100001101110000110000100001000000111001001100010110000010010111101100110111001111100010010000000010101110111

00001110110000010110101101011011100101101000011100011101001101101010000100110001001110101101111100010001111010100011010000000100

4018181242766406943

为什么echo $((${hashArray[1]} ^ ${hashArray[2]}))输出一个十进制数?它不应该是另一个大的二进制值吗?

4

3 回答 3

5

bash确实支持二进制数字,但是您的数字太大并且会被截断。要么按照mana的建议进行操作,要么拆分字符串,或者使用可以处理任意精度的库,例如 perl 的 Math::BigInt 浮现在脑海中:

异或.pl

use Math::BigInt;

$x = Math::BigInt->new("0b" . $ARGV[0]); 
$y = Math::BigInt->new("0b" . $ARGV[1]);

print $x->bxor($y)->as_bin;

为方便起见,将数字分配给变量:

x=10100100000111101011100001101110000110000100001000000111001001100010110000010010111101100110111001111100010010000000010101110111
y=00001110110000010110101101011011100101101000011100011101001101101010000100110001001110101101111100010001111010100011010000000100

运行:

perl xor.pl $x $y

输出:

0b10101010110111111101001100110101100011101100010100011010000100001000110100100011110011001011000101101101101000100011000101110011
于 2012-09-28T09:15:47.893 回答
4

像这样“按位”进行操作:

#!/bin/bash

a="101"
b="011"

out=""
for ((i=0; i < ${#a}; i++ )); do
   out=${out}$((${a:$i:1} ^ ${b:$i:1}))
done

echo ${a} ^ ${b} = $out

输出:

101 ^ 011 = 110

编辑:输入需要具有相同的长度!

于 2012-09-28T07:36:41.950 回答
0

bc按位做,首先得到文件 logic.bc :

wget http://phodd.net/gnu-bc/code/logic.bc

测试异或()

x=10100100000111101011100001101110000110000100001000000111001001100010110000010010111101100110111001111100010010000000010101110111
y=00001110110000010110101101011011100101101000011100011101001101101010000100110001001110101101111100010001111010100011010000000100

echo "ibase=2;obase=2;xor($x,$y)" | bc -l logic.bc

结果:

10101010110111111101001100110101100011101100010100011010000100001000110100100011110011001011000101101101101000100011000101110011
于 2016-12-20T18:20:28.860 回答