binary to decimal (only 8 bit / 1 byte) from 00000000 to 11111111
:global bin2dec do={
:local bin $1
:local dec 0
:local mol 1
:if (!($bin~"^[0-1]{8}\$")) do={:return 0}
:for pos from=1 to=8 do={
:local temp [:tonum [:pick $bin (8 - $pos) (8 - $pos + 1)]]
:set dec ($dec + ($temp * $mol))
:set mol ($mol * 2)
}
:return $dec
}
binary to hexadecimal (only 8 bit / 1 byte) from 00000000 to 11111111
the output is on 0x00 … 0xFF format, for remove the 0x simplu remove 0x on last “:return”
:global bin2hex do={
:local bin $1
:local dec 0
:local mol 1
:if (!($bin~"^[0-1]{8}\$")) do={:return "0x00"}
:for pos from=1 to=8 do={
:local temp [:tonum [:pick $bin (8 - $pos) (8 - $pos + 1)]]
:set dec ($dec + ($temp * $mol))
:set mol ($mol * 2)
}
:local hexadec "0"
:local remainder 0
:local hexChars "0123456789ABCDEF"
:if ($dec > 0) do={:set hexadec ""}
:while ( $dec > 0 ) do={
:set remainder ($dec % 16)
:set dec (($dec-$remainder) / 16)
:set hexadec ([:pick $hexChars $remainder].$hexadec)
}
:if ([:len $hexadec] = 1) do={:set hexadec "0$hexadec"}
:return "0x$hexadec"
}
this is the version of binary to decimal that support binary signed QWORD (64 bit) and is the max supported from RouterOS
:global binQW2dec do={
:local bin $1
:local dec 0
:local mol 1
:local lgt [:len $bin]
:if (!($bin~"^[0-1]{$lgt}\$")) do={:return 0}
:for pos from=1 to=$lgt do={
:local temp [:tonum [:pick $bin ($lgt - $pos) ($lgt - $pos + 1)]]
:set dec ($dec + ($temp * $mol))
:set mol ($mol * 2)
}
:return $dec
}
this is the version of binary to hexadecimal that support binary signed QWORD (64 bit) and is the max supported from RouterOS
:global binQW2hex do={
:local bin $1
:local dec 0
:local mol 1
:local lgt [:len $bin]
:if (!($bin~"^[0-1]{$lgt}\$")) do={:return "0x00"}
:for pos from=1 to=$lgt do={
:local temp [:tonum [:pick $bin ($lgt - $pos) ($lgt - $pos + 1)]]
:set dec ($dec + ($temp * $mol))
:set mol ($mol * 2)
}
:local firstchar ""
:if ($dec < 0) do={
:local chk (($dec & 0x7000000000000000) >> 60)
:set firstchar [:pick "89ABCDEF" $chk ($chk + 1)]
:set dec ($dec & 0x0FFFFFFFFFFFFFFF)
}
:local hexadec "0"
:local remainder 0
:local hexChars "0123456789ABCDEF"
:if ($dec > 0) do={:set hexadec ""}
:while ( $dec > 0 ) do={
:set remainder ($dec % 16)
:set dec (($dec-$remainder) / 16)
:set hexadec ([:pick $hexChars $remainder].$hexadec)
}
:if ($firstchar != "") do={
:set hexadec "00000000000000$hexadec"
:set hexadec "$firstchar$[:pick $hexadec ([:len $hexadec] - 15) [:len $hexadec]]"
}
:return "0x$hexadec"
}