Solved

# Hex to Binary Conversion routine

Posted on 2000-01-28
Medium Priority
386 Views
Hi,
Does anybody have a Hex to Binary proc already written.  I know I could do it by parsing out the input string and then using a big case statement, but I'm sure there's a better/quicker way.  Also, I don't really have time to write it in the next few days.  I'm running ksh on an aix box.
Thanks,
Bret
0

Accepted Solution

cotec1 earned 300 total points
ID: 2397722
I can't rember where I found this but I think it will do what you want (and more).

Msg () {    for i    do echo "\$PN: \$i" >&2    done}
Fatal () { Msg "\$@"; exit 1; }PrintBases () {    # Determine base of the number
for i    do      case "\$i" in          0b*)            ibase=2;;      # binary
0x*|[a-f]*|[A-F]*)      ibase=16;;      # hexadecimal          0*)                  ibase=8;;      # octal
[1-9]*)            ibase=10;;      # decimal          *)            Msg "illegal number \$i - ignored"
continue;;      esac
# Remove prefix, convert hex digits to uppercase (bc needs this)
number=`echo "\$i" | sed -e 's:^0[bBxX]::' | tr '[a-f]' '[A-F]'`
# Convert number to decimal      dec=`echo "ibase=\$ibase; \$number" | bc`
case "\$dec" in          [0-9]*)      ;;                  # number ok          *)            continue;;            # error: ignore
esac      # Print all conversions in one line      echo `bc <<!
obase=16; "hex="; \$dec          obase=10; "dec="; \$dec
obase=8;  "oct="; \$dec          obase=2;  "bin="; \$dec!    ` | sed -e 's: :      :g'
done}while [ \$# -gt 0 ]do    case "\$1" in      --)      shift; break;;      -h)      Usage;;
-*)      Usage;;      *)      break;;                  # first number    esac    shiftdoneif [ \$# -gt 0 ]then
PrintBases \$line    donefi
0

Author Comment

ID: 2398212
Thanks,
b...
0

## Featured Post

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.