Tiny Bash Functions to Convert Between Numeric Representations

I have these functions in my aliases file. They make it easy to convert between hex, binary and decimal representations of numbers. You might find it useful.

Just add these to your aliases file (imported from ~/.bashrc):

1
2
3
4
5
6
function h2d { echo "obase=10; ibase=16; $( echo "$*" | sed -e 's/0x//g' -e 's/\([a-z]\)/\u\1/g' )" | bc; }
function h2b { echo "obase=2; ibase=16; $( echo "$*" | sed -e 's/0x//g' -e 's/\([a-z]\)/\u\1/g' )" | bc; }
function b2d { echo "obase=10; ibase=2; "$*"" | bc; }
function b2h { echo "0x$(echo "obase=16; ibase=2;"$*"" | bc)"; }
function d2b { echo "obase=2; ibase=10; "$*"" | bc; }
function d2h { echo "0x$(echo "obase=16; ibase=10; "$*"" | bc)"; }

Now you should be able to use it like this:

h2d 0xff

The output will be 255 in this case.

h2b is for “hex to binary”, the others are similar (h: hex, b: binary, d: decimal)

Enjoy ;)

If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

Related posts:

  1. A Bash Script to Convert brainfuck Code Into C
  2. Strip the File Name Suffix off a Bash Variable
  3. Share Code Snippets Easily From the Command Line
  4. Send Self Reminders To Your Email From The Command Line
  5. Convert camelCase to Underscores Using sed

Tags: , ,

Friday, June 12th, 2009 Bash

Leave a Reply

my email
Already a member?
Login
Login using Facebook:
Last visitors
my photo
Hi,
My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and am currently studying for a BSc. in electrical engineering at The Electrical Engineering school , Technion , Israel.
I work at the verification dept. in Mellanox Technologies Ltd.
I love Linux, the Command Line and the OpenSource Community.
I used to write Poems (Arabic) when I was able to find time for this.
June 2009
S M T W T F S
« May   Jul »
 123456
78910111213
14151617181920
21222324252627
282930  
Opensource Logo
SEO Powered by Platinum SEO from Techblissonline

Twitter links powered by Tweet This v1.6.1, a WordPress plugin for Twitter.