我想在bash中實現一個CRC16校驗和。我正從現有的C++代碼移植。我快到了,但我得到了不同的答案。crc16算法從C++到bash
我不太明白爲什麼C++代碼和bash腳本之間的校驗和是不同的。
另一組眼睛將是一個很大的幫助。
這裏是C++代碼:
uint16_t Encoder::checksum(std::string thestring)
{
uint8_t d, e, f;
uint16_t c, r, crccalc;
c = 0xffff;
for (unsigned int i = 0; i < thestring.length(); i++)
{
d = thestring[i];
e = c^d;
f = e^(e << 4);
r = (c >> 8)^(f << 8)^(f << 3)^(f >> 4);
c = r;
}
c ^= 0xffff;
crccalc = c;
return crccalc;
}
這裏是我的bash代碼:
function calc_crc16()
{
string=$1
while read -d "" -n 1 ; do astring+=("$reply") ; done <<< "$string"
cnt=${#astring[@]}
c=0xffff
for ((x=0;x<$cnt;x++)); do
char=${astring[$x]}
e=$(($c^$char))
s=$(($e << 4))
f=$(($e^$s))
t1=$(($c >> 8))
t2=$(($f << 8))
t3=$(($f << 3))
t4=$(($f >> 4))
r1=$(($t1^$t2^$t3^$t4))
c=$r1
done
c=$c^0xffff
echo "checksum = $c"
}
難道要有事做的整數的大小?我猜在bash中我沒有太多可以做的事情。
我得到一個實際的數字,但它不符合我知道正常工作的C++。有沒有人看到任何我可能會搞砸的東西?
編寫一個快速測試,以查看C++ vs bash中的max int。祝你好運。 – shellter 2011-12-19 16:36:47
我覺得我這裏最大的問題是***爲什麼*** – Sorpigal 2011-12-19 17:20:31