开发者

Hex to Dec conversion (pipe with sed)

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'`

Update:

This works fine:

endi=`echo dede0a01 | sed 's,\(..\)\(.开发者_JAVA百科.\)\(..\)\(..\),\4\3\2\1,g' | tr '[a-z]' '[A-Z]'`
echo "ibase=16; $endi" | bc

But I'm curious whether this is possible with one line?


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} ))


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 ((...)))


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜