LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 07-08-2008, 05:23 AM   #1
gaynut
LQ Newbie
 
Registered: Jan 2008
Posts: 27

Rep: Reputation: 15
Question hexa,binary,octal additions in shell scripting


hi ,

can anybody tell me how to add,sub,mul,division functions for octal,hexadecimal,binary numbers?

thanks

~ gaynut
 
Old 07-08-2008, 05:50 AM   #2
nx5000
Senior Member
 
Registered: Sep 2005
Location: Out
Posts: 3,307

Rep: Reputation: 57
One way is to use iBase and oBase with bc:

Octal:
echo "obase=8;8+8" | bc -l
20

Hex:
echo "obase=16;8+8" | bc -l
10

Bin:
echo "obase=2;1+1" | bc -l
10

From hex to binary:
echo "ibase=16;obase=2;15*1A" | bc -l
1000100010



Going from decimal to octal back to decimal:
echo "ibase=2;obase=2;10*11;obase=1010;ibase=1010;15*10" | bc -l
110
150

Last edited by nx5000; 07-08-2008 at 05:51 AM.
 
Old 07-08-2008, 08:54 AM   #3
smoked kipper
Member
 
Registered: May 2008
Location: UK
Distribution: Slackware,Slamd64
Posts: 81

Rep: Reputation: 15
You can do it in the shell with arithmetic expansion, if integers are sufficient.

Code:
# echo $(( 0x100 / 010 ))
32
It can handle any base using "base#number" syntax, so for binary:

Code:
# echo $(( 2#10000 / 4 ))
4
 
Old 07-09-2008, 12:40 AM   #4
gaynut
LQ Newbie
 
Registered: Jan 2008
Posts: 27

Original Poster
Rep: Reputation: 15
thank u

~ gaynut
 
  


Reply

Tags
handling, numbers, unix


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
LXer: Terminal functions for shell scripting with Shell Curses LXer Syndicated Linux News 0 03-26-2008 11:50 PM
Shell Scripting: Getting a pid and killing it via a shell script topcat Programming 15 10-28-2007 02:14 AM
teaching shell scripting: cool scripting examples? fax8 Linux - General 1 04-20-2006 04:29 AM
shell interface vs shell scripting? I'm confused jcchenz Linux - Software 1 10-26-2005 03:32 PM
C, read 8 bit octal numbers, convert to 24 bit binary bamalabs Programming 3 01-20-2004 09:59 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 05:41 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration