【问题标题】:Weird "expr:Division by Zero" output when running through a while loop通过while循环运行时奇怪的“expr:除以零”输出
【发布时间】:2022-10-17 05:41:47
【问题描述】:

问候 我目前正在开发一个函数,它将每个十进制转换为二进制而不使用 awk sed printf xxd od perl ibase, obase, bc 但是,该函数设法将十进制转换为二进制,但由于某种原因,它在转换后的二进制末尾输出“expr:除以零”

我试图删除 expr 并将其设置为普通公式,但它分发了另一个错误,所以我别无选择,因为它是将十进制转换为二进制的壁橱的东西

for i in $d do #$d is the decimal
num = $d #decimal number
div = 128 #it is the power number (we should start dividing by 128)
sec = 0 #to run the loop 8 times 
while [[ $seq -ne 9 ]] 
do 
    bin=`expr $num / $div`
    echo -n "$bin" # we can add the replacing x and space here 
    rem=`expr $num % $div` # gets the remainder
    div=$(expr $div / 2) #to get the decreasing power of 2 
    num=$rem #next the num should be equal to the remainder 
    sec=$(sec + 1) 
done
done 

#OUTPUT
Output :  11111000expr:division by zero

任何提示将不胜感激

【问题讨论】:

  • 通过将 sec 设置为 0 并循环直到 sec 为 9,即循环 9 次,而不是 8 次。
  • @sj95126 感谢您的注意,我把它降到了 8,不幸的是,输出聚集在一起,而不是将每个转换后的二进制文件分成自己的列。

标签: bash loops shell


【解决方案1】:

这里有很多错误,从简单的语法开始。如果你想使用纯bash从十进制表示转换为二进制表示,你可以使用这个脚本:

#!/bin/bash

dec=123456 # for example
bin=
n=$dec
while ((n)); do
    bin=$((n & 1))$bin
    ((n >>= 1))
done

echo "$dec(decimal) = ${bin:-0}(binary)"

这应该适用于所有可以用 63 位表示的非负整数(除非您的 bash 版本非常旧)。

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    相关资源
    最近更新 更多