I have a hex value (0x0020004E0000 ... which is the base address to a hardware address). I need to add 0x04 to the base for each register. I have been doing this by first converting the base address to a base 10 number, then adding 4 to that value. The sum I then take and convert back to hex all via the string class .to_s and .to_i.

Is there a better way to do this so I'm not converting back-and-forth between base 10 and base 16 all the time? (FYI, in my previous AppleScript script, I punted hex math to the OS and let bc take care of the addition for me).

Why are you converting it back and forth? Keep it as a number and only do the final conversion to a hexadecimal string when you need to. (If you need to do this every time, then there is no better way.)
–
minitech♦Jun 20 '12 at 17:55

I'm picking it up as a string, never realized I could leave it as 0x... and have Ruby understand it was hex.
–
Wayne BrissetteJun 20 '12 at 18:00

3 Answers
3

this seems to work by internally converting the hex number to a decimal. I don't think I was clear enough... I still need to hex value to stay as a hex (or convert it back to hex) so I can use it in a string where it would show the hex value.
–
Wayne BrissetteJun 20 '12 at 18:05

@WayneBrissette: "Internally converting the number to decimal" makes no sense. You're missing the point and confusing representation with value. 4 is 4 no matter how you say it.
–
Ed S.Jun 20 '12 at 18:06

Ed, you're absolutely correct. What I was missing was that Ruby is doing stuff for me that I missed. Thanks for pointing that out! I knew I should have used irb to mess around more.
–
Wayne BrissetteJun 20 '12 at 18:10

A number is a number is a number, no matter how it is represented internally or displayed to the user. Just add them as you would any other number. If you want to view them as Hex later then fine; format them for output.

You are confusing representation with value. Ruby can parse a number represented in Hex just as well as it can parse a decimal, binary, or octal value.