views:

48

answers:

5

How can i convert my Hex value to Dec value using pipe after sed.

Conversion from 'litte endian' to 'big endian'

dec_value=`echo dede0a01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g'`
A: 

bc accepts all caps. Assuming you can provide it all caps:

endi=`echo DEDE0A01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g'`
echo "obase=10; $endi" | bc

Prints 1099999

Else if you run bc before you convert, it prints 99990901.

pavanlimo
That's converting the hex value dede0a01 to decimal. But first i need to convert it to 01a0eded (using sed) and then convert it to decimal. So how can i use bc after sed ?
Robertico
You mean convert 'dede0a01' to '10a0eded' not '01a0eded', or not?
Alexander
Use `bc` before you convert then!. Ultimately you will need to use `bc`, before or after.
pavanlimo
dec_value=`echo dede0a01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g'` makes the conversion to: 010adede (sorry for the typo). After that i need to convert that to 17489630. So how can is use a pipe after sed to make the conversion from 010adede to 17489630 ? Tried bc but can get it work.
Robertico
It appears that your hex code is not valid, cuz' bc accepts all caps.
pavanlimo
When i use: echo "ibase=16; 010ADEDE" | bc (ibase instead of obase, and all capital) the conversion works. But i want to add the conversion after sed. So how to use a pipe after sed and then bc.If that's not possible i can use a variable with bc.Tried that already but bc doesn't seems to accept a variable.
Robertico
A: 
endi=`echo dede0a01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g' | tr '[a-z]' '[A-Z]'`
echo "ibase=16; $endi" | bc

Works fine. But I'm curious whether this is possible with one line.

Robertico
Sure. Why not?echo "ibase=16; $(echo dede0a01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g' | tr '[a-z]' '[A-Z]')" | bc
bot403
A: 

Do your tr before the sed and have sed add the ibase=16; before piping it all into bc:

dec_value=$(echo dede0a01 | tr '[a-z]' '[A-Z]' | sed 's,\(..\)\(..\)\(..\)\(..\),ibase=16;\4\3\2\1,g' | bc)

If you're using Bash, ksh or zsh, you don't need tr and bc:

(( dec_value = 16#$(echo dede0a01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g') ))

or without echo and sed, too:

hex=dede0a01
(( dec_value = 16#${hex:6:2}${hex:4:2}${hex:2:2}${hex:0:2} ))
Dennis Williamson
+1  A: 

Here's a solution that doesn't shell out to bc, and uses only portable, standard syntax, nothing Bash, zsh, or ksh specific:

dec_value=`echo dede0a01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g' | (read hex; echo $(( 0x${hex} )))`

Or, somewhat more simply:

: $(( dec_value = 0x$(echo dede0a01 | sed 's,\(..\)\(..\)\(..\)\(..\),\4\3\2\1,g') ))

(You need the : $((...)) to be portable; $((...)) substitutes its result, and the : allows you to ignore it. In Bash and likely ksh/zsh, you could just use ((...)))

Brian Campbell
A: 

Thx all, for the examples. As always, there are many ways to skin a cat :-))

Robertico