为什么XORing两个大二进制数给出十进制输出?

时间:2012-09-28 06:09:47

标签: bash

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

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

给出:

10100100000111101011100001101110000110000100001000000111001001100010110000010010111101100110111001111100010010000000010101110111

00001110110000010110101101011011100101101000011100011101001101101010000100110001001110101101111100010001111010100011010000000100

4018181242766406943

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

3 个答案:

答案 0 :(得分:5)

bash 确实有support for binary numbers,但是你的数字太大而且会被截断。要么像 mana 那样建议或拆分字符串,要么使用可以处理任意精度的库,例如:想到perl的Math :: BigInt:

xor.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

答案 1 :(得分: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

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

答案 2 :(得分:0)

使用 bc 进行按位,首先获取文件logic.bc:

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

测试xor()

x=10100100000111101011100001101110000110000100001000000111001001100010110000010010111101100110111001111100010010000000010101110111
y=00001110110000010110101101011011100101101000011100011101001101101010000100110001001110101101111100010001111010100011010000000100

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

结果:

10101010110111111101001100110101100011101100010100011010000100001000110100100011110011001011000101101101101000100011000101110011