0

This is the binary evaluation and conversion part of the shell script.

elif [[ $file == file[0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1] ]]
then
    first=`echo $file | cut -c 5`
    second=`echo $file | cut -c 6`
    third=`echo $file | cut -c 7`
    fourth=`echo $file | cut -c 8`
    fifth=`echo $file | cut -c 9`
    sixth=`echo $file | cut -c 10`
    seventh=`echo $file | cut -c 11`
    eighth=`echo $file | cut -c 12`
    newname=file`expr $first \* 128 + $second \* 64 + $third \* 32 + $fourth \* 16 + $fifth \* 8 + $sixth \* 4 + $seventh \* 2 + $eighth \* 1` #this is converting the binary into decimal one bit at a time starting from the leftmost number
    while [ ! -d CATEGORY1 ]
    do
            mkdir CATEGORY1 
    done 
    mv $1/$file CATEGORY1/$newname
    echo "renamed - $file (now named  $newname) so it has been moved to the CATEGORY1 directory."

This is what I've got, but it doesn't incorporate two's complement and I can't use built-in binary features of bash.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Have a look at this post, as it discusses manual efforts. https://stackoverflow.com/questions/10278513/bash-shell-decimal-to-binary-base-2-conversion – jack_skellington May 10 '22 at 13:00

1 Answers1

1

I can't use built-in binary features of bash

I'm not sure what it means, arithmetic expressions?

First, to simplify a little, I would use a bash regex for capturing the binary number:

if [[ $file =~ ^file([01]{8})$ ]]

then you just have to convert it in whatever way you prefer:

newname=file$((2#${BASH_REMATCH[1]})) # bash builtin conversion
# or
newname=file$(echo "ibase=2;${BASH_REMATCH[1]}" | bc) # POSIX conversion

Update

For the two's complement you could do:

if [[ ${BASH_REMATCH[1]} == 1* ]]
then
    echo "ibase=2; - ( $(tr 10 01 <<< "${BASH_REMATCH[1]}") + 1)"
else
    echo "ibase=2; ${BASH_REMATCH[1]}"
fi | bc
Fravadona
  • 13,917
  • 1
  • 23
  • 35