Convert string to hexadecimal (preserving meaning)

I'm using a charting library that takes color values in hex, so white would be 0xffffff. This is a number, not a string, so doing something like "0x" + my_color_variable wouldn't work.

If I have a variable from user input that is "FFFFFF", how can I convert it to the hex number 0xffffff?

I'm using a charting library that takes color values in hex, so white would be 0xffffff. This is a number, not a string, so doing something like "0x" + my_color_variable wouldn't work.

If I have a variable from user input that is "FFFFFF", how can I convert it to the hex number 0xffffff?

the to_i method on string takes an optional argument (the base to use).

Fred

Jack Bauer wrote: [...]

Yes, but it doesn't convert it the way I need it to. What I mean is:

"FFFFFF".to_i(base=16) # => 16777215

I need it to be more like this:

"FFFFFF".whatever_magic_method # => 0xFFFFFF

So wrap it:

class String   def parse_hex     self.to_i 16   end end

What's the big deal?

Best,

Frederick Cheung wrote:

Yes, but it doesn't convert it the way I need it to. What I mean is:

"FFFFFF".to_i(base=16) # => 16777215

I need it to be more like this:

"FFFFFF".whatever_magic_method # => 0xFFFFFF

Those are exactly the same integer - the console just shows them to you in base 10 by default. to_s takes a similar base argument if you need to get a string out of it again.

Fred

Well , i just wanted to say a big THANKS!!!

to Joshua for the solution,

and Jack for posting up this problem which was the same as i was facing..

This post came up when i googled for it. And the solution mentioned above solved my problem..

Thanks a ton!! to both of you :slight_smile:

Joshua Ball wrote in post #806177: