Advertisement
pintcat

numeric - display positive decimal numbers as binary, octal & hexadecimal & their binary length

Sep 16th, 2024
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.80 KB | Software | 0 0
  1. #!/bin/sh
  2. # numeric v1.6 - display positive decimal numbers as binary, octal & hexadecimal & their binary length.
  3. # You can use other numeric systems by entering numbers with the corresponding arithmetic expression,
  4. # i.e. $((0n)) for octal or $((0xn)) for hexadecimal.
  5.  
  6. IN=$((${1##*[!0-9]*}+0)) # anything else but a decimal number is turned into 0
  7. DEC=0
  8. EXP=1
  9. while [ $IN -gt 0 ]; do # convert decimal to binary
  10.     BIN=$((IN&1))$BIN
  11.     : $((IN >>= 1))
  12. done
  13. [ ${#BIN} -lt 5 ] && LEN=5.${#BIN} || LEN=${#BIN}
  14. printf "%s %${LEN%.*}s\n" "BIN:" ${BIN:-0}
  15. while [ ${#BIN} -gt 0 ]; do # convert binary back to decimal
  16.     DEC=$(($DEC+${BIN#${BIN%?}}*$EXP))
  17.     EXP=$(($EXP*2))
  18.     BIN=${BIN%?}
  19. done
  20. printf "%s %${LEN%.*}s\n" "OCT:" $(printf "%o" $DEC) "DEC:" $DEC "HEX:" $(printf "%x" $DEC) "LEN:" ${LEN#*.}" bit"
  21.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement