Convert a hex string to a hex int

两盒软妹~` 提交于 2019-12-10 12:34:16

问题


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?


回答1:


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"



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/30563697/convert-a-hex-string-to-a-hex-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!