Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert string of hex digits to value it represents in Lua

Tags:

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).

I then need to concatenate those together such that if MSW = "00ff" and LSW = "f10a" address would be 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.

If there a way I can convert the string into hex, such that "FFFF" would become 0xFFFF?

like image 409
Sambardo Avatar asked Aug 23 '11 18:08

Sambardo


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

How do I encode a hex string?

Hex encoding is performed by converting the 8 bit data to 2 hex characters. The hex characters are then stored as the two byte string representation of the characters. Often, some kind of separator is used to make the encoded data easier for human reading.

Which function is used to find hex value of a string?

HEX() function in MySQL. HEX() : This function in MySQL is used to return an equivalent hexadecimal string value of a string or numeric Input. If the input is a string then each byte of each character in the string is converted to two hexadecimal digits.


1 Answers

You use 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.

like image 147
Nicol Bolas Avatar answered Oct 08 '22 22:10

Nicol Bolas