将hex字符串转换为hexint
我必须将hex字符串转换为hex整数,如下所示:
color = "0xFF00FF" #can be any color else, defined by functions colorto = 0xFF00FF #copy of color, but from string to integer without changes
我也可以使用RGB格式。
我不得不这样做,因为这个function如下:
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
我在这里看到存在hex整数。 有人可以帮我解决这个问题吗?
你需要为String#to_i
方法提供整数基本参数:
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"
首先,整数永远不是hex。 每个整数都有一个hex表示 ,但这是一个字符串。
要将包含带有0x
前缀的整数的hex表示forms的字符串转换为Ruby中的整数,请在其上调用函数Integer
。
Integer("0x0000FF") # => 255
2.1.0 :402 > "d83d".hex => 55357