string 如何将十六进制数字字符串转换为它在 Lua 中表示的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7165577/
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
How do I convert string of hex digits to value it represents in Lua
提问by Sambardo
I'm reading in a lot of lines of hex data. They come in as strings and I parse them for line_codes which tell me what to do with the rest of the data. One line sets a most significant word of an address (MSW), another line sets the least significant (LSW).
我正在阅读很多行的十六进制数据。它们以字符串形式出现,我将它们解析为 line_codes,它告诉我如何处理其余数据。一行设置地址的最高有效字 (MSW),另一行设置最低有效字 (LSW)。
I then need to concatenate those together such that if MSW = "00ff" and LSW = "f10a" address would be 00fff10a.
然后我需要将它们连接在一起,如果 MSW = "00ff" 和 LSW = "f10a" 地址将是 00fff10a。
This all went fine, but then I was supposed to check if address was between a certain set of values:
这一切都很好,但后来我应该检查地址是否在一组特定的值之间:
if address <= "007FFFh" and address >= "000200h" then
print "I'm in"
end
As you all probably know, Lua is not a fan of this as it gives me an error using <=
and >=
with strings.
大家可能都知道,Lua 不喜欢这个,因为它给我一个使用<=
和>=
使用字符串的错误。
If there a way I can convert the string into hex, such that "FFFF" would become 0xFFFF?
如果有一种方法可以将字符串转换为十六进制,这样“FFFF”就会变成 0xFFFF?
回答by Nicol Bolas
You use tonumber
:
你使用tonumber
:
local someHexString = "03FFACB"
local someNumber = tonumber(someHexString, 16)
Note that numbers are not in hexadecimal. Nor are they in decimal, octal, or anything else. They're just numbers. The number 0xFF is the same number as 255. "FF" and "255" are string representations of the same number.
请注意,数字不是十六进制的。它们也不是十进制、八进制或其他任何形式。他们只是数字。数字 0xFF 与 255 是相同的数字。“FF”和“255”是相同数字的字符串表示。