LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash + How to add Hexadecimal numbers (https://www.linuxquestions.org/questions/programming-9/bash-how-to-add-hexadecimal-numbers-581792/)

trscookie 09-03-2007 03:06 AM

Bash + How to add Hexadecimal numbers
 
Hi all,

How do you add two hexadecimal numbers together in bash? I have looked all over google and could not find an answer.

Thanks, trscookie.

ghostdog74 09-03-2007 03:13 AM

Code:

# echo $((0xA + 1))
11
# echo $((0xA + 2))
12
# echo $((0xA + 3))
13
# echo $((0xF + 3))
18
# echo $((0xF + 0xF))
30


trscookie 09-03-2007 03:17 AM

hi, thanks for a super speedy response but the answer is in decimal, how do you get the answer in hex?

scoban 09-03-2007 03:25 AM

You can use "bc".

Code:

$ bc -l
obase=16 # Order is important (see note below)
ibase=16 # Once you set input base all numbers are in that base

9+3
C

ibase=A  # set input base to decimal
obase=10 # set output base to decimal

9+3
12


trscookie 09-03-2007 03:49 AM

Getting the wrong result????:


Code:

adrian@adrians-laptop:~$ bc -l
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
ibase=16
obase=16
a1+1
 01


adrian@adrians-laptop:~$ bc -l
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
obase=16
ibase=16
a1+1
1


shouldn't the answer be a2? Am I doing something wrong here?

Thanks.

ghostdog74 09-03-2007 03:50 AM

Quote:

Originally Posted by trscookie (Post 2879415)
hi, thanks for a super speedy response but the answer is in decimal, how do you get the answer in hex?

Code:

# var=$((0xA + 1))
# echo $var
11
# echo 16o${var}p |dc
B


trscookie 09-03-2007 03:52 AM

Sorry, just realised that it is case sensitive, thanks for all of your help. trscookie

cfaj 09-03-2007 04:22 PM

Quote:

Originally Posted by trscookie (Post 2879415)
hi, thanks for a super speedy response but the answer is in decimal, how do you get the answer in hex?

Code:

printf "%X\n" $((0xA + 2))


All times are GMT -5. The time now is 08:58 AM.