Last active
April 30, 2017 00:42
-
-
Save Youka/863e90871081180dfa61 to your computer and use it in GitHub Desktop.
Converter between byte string and number
This file contains hidden or 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
| -- Lua 5.1 or 5.2 table unpacker | |
| local unpack = table.unpack or unpack | |
| -- Bytes to unsigned integer | |
| local function bton(s) | |
| local bytes, n = {s:byte(1,-1)}, 0 | |
| for i=0, #s-1 do | |
| n = n + bytes[1+i] * 256^i | |
| end | |
| return n | |
| end | |
| -- Unsigned integer to bytes | |
| local function ntob(n, len) | |
| local bytes = {} | |
| for i=1, len do | |
| bytes[i] = n % 256 | |
| n = math.floor(n / 256) | |
| end | |
| return string.char(unpack(bytes)) | |
| end | |
| -- Test | |
| print( | |
| bton(ntob(32767, 2)) | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment