Shaun the Sheep
Shaun the Sheep

Reputation: 5

How can I read Hexidecimal numbers with the 0x0 extension as either normal Hex numbers or integers

I'm trying to read values in i2c addresses from my raspberry pi. Through the use of i2ctools, I can take an address and store it in a variable.

reg_state=$(i2cget -y 1 0x20 0x09)
echo "$reg_state"
:~/ $ 0x0a

However, although the address reads in properly, reg_state will keep the hex extension of "0x0" and this hinders doing operations. Say 0x0a was in the register before, and I want to add "1" to that value, the operation won't complete. I think this has to do with the way I'm trying to achieve my goal. Right now my code looks like this:

7 addition(){
8   reg_state=$(i2cget -y 1 0x20 0x09)
9   i=$(echo "obase=10; $reg_state"| bc)
10  write=$(i+adj )
}
...
25
26#Main Shell Script
27
28 op=$1
29 adj=$2
30 if [ $1 -gt 0 ]
31 then
32   addition
33 fi

What I'm attempting to do is read in the value of the register at an address, convert it to a decimal number and then add it with any number I want. However, I noticed that I am unable to use echo "obase=10; $reg_state | bc" because of the presence of '0x'. When converting hex numbers without the extension everything works fine, and they can be added like normal.

That being said, is there anyway I can get rid of the '0x' part and just have what's left so I can do my arithmetic in peace?

Upvotes: 0

Views: 195

Answers (1)

Shawn
Shawn

Reputation: 52344

You shouldn't need bc to do integer math, even on hex numbers. Just use shell arithmetic expansion. echo "$(( 0xA + 1))" will display 11, for example. And if you need the result in hex:

printf "0x%X" $(( 0xA + 1))

will print 0xB.

Upvotes: 1

Related Questions