Saturday, July 5, 2014

Fletcher Checksum Calculator in Bash

Bash is quite a powerful scripting language and all UNIX machines have it.   The main problem with it is that it was initially designed to work in text mode, making it awkward to process numbers, which tend to be unexpectedly converted back to text strings.

If you need to debug a serial RS232/RS422 avionics device with control messages that end in a checksum or CRC, then it can be hard to generate the checksums.  This example calculates the Fletcher checksum of a hexadecimal message and prints the message out, so that you can copy and paste it into a serial terminal such as cutecom, minicom or screen.

Alternatively, you could print the message directly to the serial device, provided that you initialized it with stty as shown in here:

The calculator bc and the printf statement can be used to overcome these limitations.

#! /bin/bash
echo -en "Message = "

# Calculate the Hexadecimal message checksum using bc
MESSAGE="11 22 33 44 55 66"

for i in $MESSAGE
 j=$(echo "ibase=16;$i" | bc)
 printf "%x " "$j"

 SUM=$(echo "$SUM + $j" | bc)
 SUM=$(echo "$SUM%256" | bc)

 FLETCHER=$(echo "$FLETCHER + $SUM" | bc)
 FLETCHER=$(echo "$FLETCHER%256" | bc)
printf "%x " "$SUM"
printf "%x\n" "$FLETCHER"

La voila!

No comments:

Post a Comment

On topic comments are welcome. Junk will be deleted.