在Ruby中将一个整数转换为十六进制字符串

时间:2022-02-28 17:08:04

Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?

是否有一种方法可以将Ruby中的一个整数转换成它的十六进制等价?

Something like the opposite of String#to_i:

类似于字符串#to_i的反义词:

"0A".to_i(16) #=>10

Like perhaps:

像可能:

"0A".hex #=>10

I know how to roll my own, but it's probably more efficient to use a built in Ruby function.

我知道如何滚动自己的程序,但是使用内置的Ruby函数可能更有效。

5 个解决方案

#1


288  

You can give to_s a base other than 10:

你可以给to_s一个基数而不是10:

10.to_s(16)  #=> "a"

#2


82  

How about using %/sprintf:

如何使用% / sprintf:

i = 20
"%x" % i  #=> "14"

#3


64  

To summarize:

总结:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

#4


11  

Here's another approach:

这是另一个方法:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

请参阅sprintf的文档:http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

#5


2  

Just in case you have a preference for how negative numbers are formatted:

以防你对负数的格式有偏好:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"

#1


288  

You can give to_s a base other than 10:

你可以给to_s一个基数而不是10:

10.to_s(16)  #=> "a"

#2


82  

How about using %/sprintf:

如何使用% / sprintf:

i = 20
"%x" % i  #=> "14"

#3


64  

To summarize:

总结:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

#4


11  

Here's another approach:

这是另一个方法:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

请参阅sprintf的文档:http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

#5


2  

Just in case you have a preference for how negative numbers are formatted:

以防你对负数的格式有偏好:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"