Do math on output of cat

Viewed 136

I have a single byte, 0x1, inside t.data.

How would I read that file to perform bitwise math on it's contents in POSIX shell?

echo $((1 << 1))

gives 2, but

echo $(($((cat t.data)) << 1))

and var d=$(< t.data); echo $(("$d" << 1))

fail.

1 Answers

POSIX sh and Bash are not suitable for processing binary data, but you can use printf to convert back and forth between bytes and integers:

# Read the ascii value of the first byte
num=$(printf "%d" "'$(head -c 1 < t.data)")
echo "The decimal representation of the first byte is $num"

# Do some math on it
num=$(( (num << 1) & 0xFF ))
echo "After shifting by one, it became $num"

# Write back the result via an octal escape
oct=$(printf '%03o' "$num")
printf "\\$oct" > t.data
 
Related