ruby 将十六进制字符串转换为十六进制整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30563697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:44:01  来源:igfitidea点击:

Convert a hex string to a hex int

rubyliterals

提问by FrereDePute

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 herethat hexadecimal integers exist. Can someone help me with this problem?

我在这里看到存在十六进制整数。有人可以帮我解决这个问题吗?

回答by David Unric

You'd need supply integer base argument to String#to_imethod:

您需要为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"

回答by Cu3PO42

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 0xprefix to an integer in Ruby, call the function Integeron it.

要将包含带有0x前缀的整数的十六进制表示的字符串转换为Ruby 中的整数,请调用其Integer上的函数。

Integer("0x0000FF") # => 255

回答by wxianfeng

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

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