Convert a decimal number to hexadecimal and binary in a shell script Convert a decimal number to hexadecimal and binary in a shell script bash bash

Convert a decimal number to hexadecimal and binary in a shell script


The following one-liner should work:

printf "%s %08d 0x%02x\n" "$1" $(bc <<< "ibase=10;obase=2;$1") "$1"

Example output:

$ for i in {1..10}; do printf "%s %08d 0x%02x\n" "$i" $(bc <<< "ibase=10;obase=2;$i") "$i"; done1 00000001 0x012 00000010 0x023 00000011 0x034 00000100 0x045 00000101 0x056 00000110 0x067 00000111 0x078 00001000 0x089 00001001 0x0910 00001010 0x0a


So I searched for a short and elegant awk binary converter. Not satisfied considered this as a challenge, so here you are. A little bit optimzed for size, so I put a readable version below.

The printf at the end specifies how large the numbers should be. In this case 8 bits.

Is this bad code? Hmm, yeah... it's awk :-)Does of course not work with very huge numbers.

67 characters long awk code:

awk '{r="";a=$1;while(a){r=((a%2)?"1":"0")r;a=int(a/2)}printf"%08d\n",r}'

Edit: 55 characters awk code

awk '{r="";a=$1;while(a){r=a%2r;a=int(a/2)}printf"%08d\n",r}'

Readable version:

awk '{r=""                    # initialize result to empty (not 0)      a=$1                    # get the number      while(a!=0){            # as long as number still has a value        r=((a%2)?"1":"0") r   # prepend the modulos2 to the result        a=int(a/2)            # shift right (integer division by 2)      }      printf "%08d\n",r       # print result with fixed width     }'

And the asked one liner with bin and hex

awk '{r="";a=$1;while(a){r=a%2r;a=int(a/2)}printf"%08d 0x%02x\n",r,$1}'


You don't need bc. Here's a solution using only awk:

  • Fetch the bits2str function available in the manual
  • Add this minimal script:

    {    printf("%s %s %x\n", $1, bits2str($1), $1)}

This produces:

$ awk -f awkscr.awk nums 1 00000001 12 00000010 23 00000011 3