Created
September 5, 2012 22:31
-
-
Save minism/3646479 to your computer and use it in GitHub Desktop.
lua binary data packing
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
-- Fast functions for working with binary data | |
return { | |
decode_uint8 = function(str, ofs) | |
ofs = ofs or 0 | |
return string.byte(str, ofs + 1) | |
end, | |
decode_uint16 = function(str, ofs) | |
ofs = ofs or 0 | |
local a, b = string.byte(str, ofs + 1, ofs + 2) | |
return a + b * 0x100 | |
end, | |
decode_uint32 = function(str, ofs) | |
ofs = ofs or 0 | |
local a, b, c, d = string.byte(str, ofs + 1, ofs + 4) | |
return a + b * 0x100 + c * 0x10000 + d * 0x1000000 | |
end, | |
encode_uint8 = function(int) | |
return string.char(int) | |
end, | |
encode_uint16 = function(int) | |
local a, b = int % 0x100, int / 0x100 | |
return string.char(a, b) | |
end, | |
encode_uint32 = function(int) | |
local a, b, c, d = | |
int % 0x100, | |
int / 0x100 % 0x100, | |
int / 0x10000 % 0x100, | |
int / 0x1000000 | |
return string.char(a, b, c, d) | |
end, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment