从C ++来砸CRC16算法 [英] crc16 algorithm from C++ to bash
问题描述
我想实现在bash一个CRC16校验。我是从C ++ code的现有片移植。我几乎没有,但我得到不同的答案。
I am trying to implement a CRC16 checksum in bash. I'm porting from an existing piece of C++ code. I'm almost there, but I am getting different answers.
我不太明白为什么C ++ code和bash脚本之间的校验是不同的。
I don't quite see why the checksums between the C++ code and the bash script are different.
另一套的眼睛将是一个很大的帮助。
Another set of eyes would be a big help.
下面是C ++ code:
Here is the C++ code:
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 code:
And here is my bash code:
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。
Is it going to have something to do with the size of the ints? I'm guessing there's not much I can do about that in bash.
我得到一个实际的数字,但是它不符合C ++,这是我正确认识工作。有没有人看到任何东西,我可能会搞砸的事情了?
I'm getting an actual number, but it doesn't match the C++, which I know works correctly. does anyone see anything where I may be screwing things up?
推荐答案
确定。与Sorpigal的帮助下,我有一个工作版本。
ok. with Sorpigal's help, i've got a working version.
我怀疑这可以全部awk脚本,它可以更快地运行了很多内完成。我可能会尝试,明年。
i suspect this could all be done within an awk script, which may run a lot faster. i may try that next.
感谢大家的帮助。我不是说要在这里偷的解决方案,但我的工作就可以了,算起来是值得投入的。
thank you all for the help. i don't mean to steal the solution here, but i worked on it, and figure it is worth putting up.
反正,这里是一个工作版本:
anyway, here is a working version:
function calc_crc16()
{
while read -r -d "" -n 1 ; do astring+=( "$REPLY" ) ; done <<< "$1"
cnt=${#1}
c=65535
for ((x=0;x<$cnt;x++)); do
char=$(printf '%d' \'"${1:$x:1}")
e=$(((c ^ char) & 0x00FF))
s=$(((e << 4) & 0x00FF))
f=$(((e ^ s) & 0x00FF))
r1=$(((c >> 8) ^ (f << 8) ^ (f << 3) ^ (f >> 4)))
c=$r1
done
c=$((c ^ 0xffff))
echo "checksum = $c"
}
这篇关于从C ++来砸CRC16算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!