M BUZZ CRAZE NEWS
// general

Convert only characters to decimal in hexa string

By Sarah Rodriguez

I have the following hexa string

17a62

I want to convert it to decimal. I am using the following approach:

echo $((16#17a62))

It results in

96866

but i dont want this, i just want to replace the "alphabet character" in the string with its decimal value. Like decimal value of a hex is 10 so i want the output to be like:

171062

How can i achieve this ? any help would be much appreciated.

3

2 Answers

Could do it with sed:

$ printf %d $(sed 's/./0x& /g' <<< 17a26b12)

If Perl is an option, you could do something like this:

$ echo 17a62 | perl -pe 's/[a-f]/hex $&/e'
171062

If you really need to do this natively in the shell, then with bash:

$ hexa=17a62
$ [[ $hexa =~ ([0-9]*)([a-f])([0-9]*) ]] && printf '%d%d%d\n' "${BASH_REMATCH[1]}" $((16#"${BASH_REMATCH[2]}")) "${BASH_REMATCH[3]}"
171062

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy