2012-09-28 64 views
3

我想異或兩個大的二進制值。然而,爲什麼XORing兩個較大的二進制數字會給出十進制輸出?

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

給出:

10100100000111101011100001101110000110000100001000000111001001100010110000010010111101100110111001111100010010000000010101110111 

00001110110000010110101101011011100101101000011100011101001101101010000100110001001110101101111100010001111010100011010000000100 

4018181242766406943 

爲什麼echo $((${hashArray[1]}^${hashArray[2]}))輸出的十進制數?它不應該是另一個大的二進制值嗎?

+3

...整數溢出? – nneonneo

回答

3

做吧 「按位」 這樣的:

#!/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 

編輯:輸入都需要具有相同的長度!

5

bash確實有support for binary numbers,但是您的數字太大而且會被截斷。或者按法力值建議或拆分字符串或使用可以處理任意精度的庫,例如Perl的數學:: 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 
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 
相關問題