Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add Hex values in Ruby

Tags:

ruby

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).

like image 310
Wayne Brissette Avatar asked Dec 20 '22 20:12

Wayne Brissette


2 Answers

0x0020004E0000 + 0x04

or simply

0x0020004E0000 + 4

like image 119
Matthew Ratzloff Avatar answered Jan 06 '23 04:01

Matthew Ratzloff


You have four ways of representing integer values in Ruby

64        # integer
0x40      # hexadecimal
0100      # octal
0b1000000 # binary

# These are all 64.
like image 28
tomferon Avatar answered Jan 06 '23 03:01

tomferon