Hex, Octal and Binary shell conversions

Hex, Octal and Binary shell conversions

In scripting, it is common to find a need hexadecimal (hex or base 16) numbers, and occasionally binary numbers. Converting can be tricky without some tips. You can use printftypeset and even bc as conversion tools. Here are some ideas:

HEX conversions

  • Shell:
    HEX=1fa
    echo $((16#$HEX))
    506
        or: DECIMAL=$((16#$HEX))
  • typeset (shell):
    typeset -i16 HEX=506
     (convert decimal to hex)
    echo $HEX
    16#1fa
     (typeset adds the base 16# and uses lowercase hex chars)
  • printf:
    printf “%dn” 0x1fa
     (printf understands 0x for hex numbers)
    506and decimal to hex for printf:
    printf “%X %xn” 506 506 (printf uses X and x for UPPER and lower case)
    1FA 1fa
    or:

    printf “0x%X 0x%xn” 506 506
     (add the 0x to flag as hex)
    0x1FA 0x1fa
  • bc:
    HEX=1FA    
         (mandatory UPPERCASE for bc)echo “ibase=16n$HEX” | bc
    506

OCTAL conversions

  • Shell:
    OCTAL=772
    echo $((8#$OCTAL))
    506
        or: DECIMAL=$((8#$OCTAL))
  • typeset (shell):
    typeset -i8 OCTAL=506 (convert decimal to octal)
    echo $OCTAL
    8#772
     (typeset adds the base 8#)
  • printf:
    printf “%dn” 0772 (printf understands 0 prefix for octal numbers)
    506and decimal to octal for printf:
    printf “%on” 506
    772
    or:
    printf “0%on” 506 (add the leading 0 to flag as octal)
    0772
  • bc:
    OCTAL=772
    echo “ibase=8n$OCTAL” | bc
    506

BINARY conversions

  • Shell:
    BINARY=111111010
    echo $((2#$BINARY))
    506
        or: DECIMAL=$((8#$BINARY))
  • typeset (shell):
    typeset -i2 BINARY=506 (convert decimal to octal)
    echo $BINARY
    2#111111010
     (typeset adds the base 2#)
  • bc:
    BINARY=111111010
    echo “ibase=2n$BINARY” | bc
    506

– See more at: http://serviceitdirect.com/blog/hex-octal-and-binary-shell-conversions#sthash.DCLsFU93.dpuf


Tags: