Created
July 29, 2014 13:08
-
-
Save imp-guru/62f8036e3105fc8cc830 to your computer and use it in GitHub Desktop.
Hex to Integer conversion for Electric Imp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function to convert a hexidecimal string to an integer | |
function hex2int(x) | |
{ | |
// Sanitize the string to all upper | |
local hex = x.tostring().toupper(); | |
// Create a lookup table for the hex digits, the index represents the decimal value | |
local hexChars = "0123456789ABCDEF"; | |
// Initialize a variable for the return value | |
local result = 0; | |
// Get the length of the hex string | |
local length = hex.len(); | |
// Iterate through each character of the hex string | |
for (local i = 0 ; i < length; i++) | |
{ | |
// use the find function to convert the current hex digit to an integer | |
// then use the location in the string to determine the power of 16 | |
// multiply and accumulate to the return value | |
result += hexChars.find(hex[length-i-1].tochar())*math.pow(16,i); | |
} | |
// When loop is complete send back the result | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment