6

I want to convert a decimal number (loop index number) in a bash script to hexadecimal to be used by another command. Something like:

for ((i=1; i<=100; i++))
do

     a=convert-to-decimal($i)
     echo "$a"

done

Where a should be hexadecimal with four digits and hex identifier. For example if value of i is 100, the value of a should be 0x0064. How to do it?

asm_nerd1
  • 445
  • 1
  • 7
  • 23
  • 2
    Possible duplicate of [Convert decimal to hexadecimal in UNIX shell script](http://stackoverflow.com/questions/378829/convert-decimal-to-hexadecimal-in-unix-shell-script) – TayTay Feb 10 '16 at 16:03
  • 1
    `printf "%#06x" 100` → `0x0064` – Biffen Feb 10 '16 at 16:05

2 Answers2

4

You can use printf.

$ printf "0x%04x" 100
0x0064

In your example you'd probably use a="$(printf '0x%04x' $i)".

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
1

That's what you're looking for

for i in seq 1 100; do printf '%x\n' $i done

Alex Nikas
  • 83
  • 8