# Squirrel hex to integer

As a Squirrel newcomer, I’m wondering whether there’s a way to convert a hex string to an integer.
my string is something like “0xff”.
I’ve tried “0xff”.tointeger(), but this returns 0, which isn’t the desired result at all.
I’m trying to convert a series of hex values contained in a file to a series of integers, and am wondering whether there’s a built in function to do this a hex byte at a time, rather than writing such a function.

Thanks for any help anyone may be able to offer,
Toby

There’s no scanf() equivalent, so I’m afraid you’ll need to write a function There is an example on the devwiki that might help you - http://devwiki.electricimp.com/doku.php?id=webcolor

`// Convert hex string to an integer
function hexToInteger(hex)
{
local result = 0;
local shift = hex.len() * 4;

``````// For each digit..
for(local d=0; d<hex.len(); d++)
{
local digit;

// Convert from ASCII Hex to integer
if(hex[d] >= 0x61)
digit = hex[d] - 0x57;
else if(hex[d] >= 0x41)
digit = hex[d] - 0x37;
else
digit = hex[d] - 0x30;

// Accumulate digit
shift -= 4;
result += digit << shift;
}

return result;
``````

}
`

Hi. I want to convert a integer (1 Byte UART data) to hex. Because I want to log (serverlog) the UART data in hex format.

You can use the format() function which works the same as c’s printf:

`server.log(format("0x%02x", yourByte));`

Example:

`server.log(format("0x%02x", 32)); //Outputs: 0x20`