FrereDePute FrereDePute - 4 months ago 5
Ruby Question

Convert a hex string to a hex int

I have to convert a hexadecimal string to a hexadecimal integer, like this:

color = "0xFF00FF" #can be any color else, defined by functions
colorto = 0xFF00FF #copy of color, but from string to integer without changes

I can have RGB format too.

I'm obliged to do this because this function goes after :

def i2s int, len
i = 1
out = "".force_encoding('binary')
max = 127**(len-1)

while i <= len
num = int/max
int -= num*max
out << (num + 1)
max /= 127
i += 1


I saw here that hexadecimal integers exist. Can someone help me with this problem?


You'd need supply integer base argument to String#to_i method:

irb> color = "0xFF00FF"
irb> color.to_i(16)
=> 16711935
irb> color.to_i(16).to_s(16)
=> "ff00ff"
irb> '%#X' % color.to_i(16)
=> "0XFF00FF"