Some reasoning on this...
this function already exist on RouterOS,
but I don't want to belittle anyone's work, it was just to let find out.
using this example, the second line is for simulating one string readed from other variables.
:put 0xFF85
:put [:tonum "0xFF85"]
The eworm function works, obviously :))
and this is a very great idea for solve mixed, upper or lowercase:
:local Hex "0123456789abcdef_eworm.de_ABCDEF"
[:find $Hex ... ] % 16
:global HexToNum do={
:local Input [:tostr $1]
:local Hex "0123456789abcdef_eworm.de_ABCDEF"
:local Multi 1; :local Return 0
:for I from=([:len $Input] - 1) to=0 do={
:set Return ($Return + (([:find $Hex [:pick $Input $I]] % 16) * $Multi))
:set Multi ($Multi * 16)
}
:return $Return
}
:put [$HexToNum "0xFF85"]
whe have the same results:
But is not what is wanted:
-123
2 Byte signed go to
-32.768 to 0 to 32767 (65536 possible values)
written on hex
(0x8000 + 0x0 = 8000) to (0x8000 + 0x7FFF = 0xFFFF) to 0x0 to 0x7FFF, simply most significative bit set = negative value
for obtain rapidly the wanted value, if decimal value from hex is > 32767, subtract 65536 to it, instead use directly the results.
65413 > 32767 ? Yes then 65413 - 65536 =
-123
Using directly RouterOS (without create a function or add some sanity ckeck from the provided value):
:global lazyvar "FF85"
:set lazyvar [:tonum ("0x".$lazyvar)]
:if ($lazyvar > 32767) do={:set lazyvar ($lazyvar - 65536)}
:put $lazyvar
:set lazyvar
Using
Earthworm Jim*** function (without add some sanity ckeck from the provided value):
:global SingleWordHexToNum do={
:local Input [:tostr $1]
:local Hex "0123456789abcdef_eworm.de_ABCDEF"
:local Multi 1; :local Return 0
:for I from=([:len $Input] - 1) to=0 do={
:set Return ($Return + (([:find $Hex [:pick $Input $I]] % 16) * $Multi))
:set Multi ($Multi * 16)
}
:if ($Return > 32767) do={ :return ($Return - 65536) } else={ :return $Return }
}
:put [$SingleWordHexToNum "0xFF85"]
***: do not offend, is one of my preferred game when I'm young, and is still on my heart