繁体   English   中英

使用二进制补码将文件名(例如 file01010101)从十进制转换为二进制,而不使用 bash 中的内置二进制函数

[英]convert a filename eg file01010101 from decimal to binary using two's complement, without using built in binary function in bash

这是 shell 脚本的二进制评估和转换部分。

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."

这就是我所拥有的,但它不包含二进制补码,我不能使用 bash 的内置二进制特性。

我不能使用 bash 的内置二进制功能

我不确定它是什么意思,算术表达式?

首先,为了简化一点,我将使用 bash 正则表达式来捕获二进制数:

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

then你只需要以你喜欢的任何方式转换它:

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

更新

对于二进制补码,您可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM