Correct way to convert hex to int


#1

I saw this error come through, unfortunately I don’t have the value it processed to re-produce the error but wondered if this was the correct way to convert a hex value to an integer?

2019-03-06T14:29:40.288 +00:00 [Device] ERROR: arith op + on between ‘integer’ and ‘null’
2019-03-06T14:29:40.288 +00:00 [Device] ERROR: in hextoint device_code:851

function hextoint(m, index, len) { // convert ascii hex to int
    local n = 0;
    for (local i = 0; i < len; i++) {
        n = n << 4;
        n+="0123456789ABCDEF".find(m.slice(index+i,index+i+1));
    }
    return n;
}

Not my code for clarity :stuck_out_tongue: I wonder if maybe the hex wasn’t of the length expected so the find produced the null?


#2

That’s one way of doing it… printing the string you’re trying to convert (and the value of index) would help. Possibly the hex is lowercase in the string?

The tointeger() method on a string will convert to hex if the string starts with “0x”. May just be easier to do:

function hextoint(m, index, len) {
  return ("0x"+m.slice(index, index+len)).tointeger();
}

(I’ve not tried that but think it should work. See https://developer.electricimp.com/squirrel/string/tointeger