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.
我也可以使用RGB格式。
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?
我在这里看到存在十六进制整数。有人可以帮我解决这个问题吗?
3 个解决方案
#1
19
You'd need supply integer base argument to String#to_i
method:
你需要为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"
#2
8
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.
要将包含带有0x前缀的整数的十六进制表示形式的字符串转换为Ruby中的整数,请在其上调用函数Integer。
Integer("0x0000FF") # => 255
#3
4
2.1.0 :402 > "d83d".hex => 55357
2.1.0:402>“d83d”.hex => 55357
#1
19
You'd need supply integer base argument to String#to_i
method:
你需要为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"
#2
8
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.
要将包含带有0x前缀的整数的十六进制表示形式的字符串转换为Ruby中的整数,请在其上调用函数Integer。
Integer("0x0000FF") # => 255
#3
4
2.1.0 :402 > "d83d".hex => 55357
2.1.0:402>“d83d”.hex => 55357