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?

2

2 Answers 2

4

You can use printf.

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

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

Sign up to request clarification or add additional context in comments.

5 Comments

Or printf -v a '0x%04x' $i instead of process substitution.
@BenjaminW. You certainly mean command substitution. But your point is correct.
@gniourf_gniourf I absolutely do!
Actually 0x can be left off. # flag adds this automatically. So printf "%#06x" 100 gives 0x0064. The only question remains if the OP needs lower case of upper case hex digits. In the later case the X specifier should be used.
@TrueY: feel free to edit the answer to improve it! (or write your own answer).
1

That's what you're looking for

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.