Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a hex string to a hex int

Tags:

ruby

literals

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
  end

  out
end

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

like image 613
FrereDePute Avatar asked May 31 '15 23:05

FrereDePute


People also ask

How do you convert hex to int in Python?

The most common and effective way to convert hex into an integer in Python is to use the type-casting function int() . This function accepts two arguments: one mandatory argument, which is the value to be converted, and a second optional argument, which is the base of the number format with the default as 10 .

Does atoi work for hex?

The atoi() and atol() functions convert a character string containing decimal integer constants, but the strtol() and strtoul() functions can convert a character string containing a integer constant in octal, decimal, hexadecimal, or a base specified by the base parameter.

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.


3 Answers

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"
like image 119
David Unric Avatar answered Oct 17 '22 10:10

David Unric


First off, an integer is never hexadecimal. Every integer has a hexadecimal representation, but that is a string.

To convert a string containing a hexadecimal representation of an integer with the 0x prefix to an integer in Ruby, call the function Integer on it.

Integer("0x0000FF") # => 255
like image 35
Cu3PO42 Avatar answered Oct 17 '22 09:10

Cu3PO42


2.1.0 :402 > "d83d".hex => 55357

like image 11
wxianfeng Avatar answered Oct 17 '22 09:10

wxianfeng