PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

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

 August 10, 2022     decimal, hex, i2c, shell, type-conversion     No comments   

Issue

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?


Solution

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.



Answered By - Shawn
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing