Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print the decimal value to hex values in shell script

Tags:

shell

I have a requirement of having a string which has a decimal value. For e.g., '0 2930 0'. Now , when i convert it to hex, it should say '0000 0B72 0000'. i'm able to convert the values to hex using split and obase=16 with bc, i'll get the answer as '0 B72 0'. What i needed is to get the value '0000 0B72 0000'. Can anyone help shed some light on this?

Here is what i've done:

s1 ='2930'
echo after converting it to hexadecimal
s=`echo "obase=16; $s1" |bc`
echo $s
like image 516
user3202415 Avatar asked Mar 21 '23 22:03

user3202415


2 Answers

Use printf for getting the output in the desired format:

$ printf "%04x " 0 2930 0
0000 0b72 0000
like image 181
devnull Avatar answered Mar 23 '23 11:03

devnull


Using bc as you have,

WANTED=456  ; echo "obase=16 ;$WANTED"|bc

and multiples

WANTED="{456 ;12 ;32000}"  ; echo "obase=16 ;$WANTED"|bc
like image 20
X Tian Avatar answered Mar 23 '23 11:03

X Tian