Created
July 22, 2019 09:16
-
-
Save pcornier/133b9c5019a103d568eba257a24c9977 to your computer and use it in GitHub Desktop.
LUA FFI byte union struct
This file contains 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
local ffi = require 'ffi' | |
local ct = [[ | |
union { | |
struct { | |
uint8_t nlow:4; | |
uint8_t nhigh:4; | |
}; | |
struct { | |
uint8_t b0:1; | |
uint8_t b1:1; | |
uint8_t b2:1; | |
uint8_t b3:1; | |
uint8_t b4:1; | |
uint8_t b5:1; | |
uint8_t b6:1; | |
uint8_t b7:1; | |
}; | |
uint8_t value; | |
} | |
]] | |
local _byte = ffi.metatype(ct, { | |
__call = function(obj, p1, p2) | |
local lut = { | |
[0] = 'b0', | |
[1] = 'b1', | |
[2] = 'b2', | |
[3] = 'b3', | |
[4] = 'b4', | |
[5] = 'b5', | |
[6] = 'b6', | |
[7] = 'b7' | |
} | |
if p2 == nil then | |
return obj[lut[p1]] | |
else | |
local b = 0 | |
local s = p1 - p2 | |
for i=p1,p2,-1 do | |
b = bit.bor(b, bit.lshift(obj[lut[i]], s)) | |
s = s - 1 | |
end | |
return b | |
end | |
end; | |
}) | |
test = ffi.new(_byte) | |
test.value = 0xab | |
assert(test(3, 0) == test.nlow, 'invalid') | |
assert(test(7, 4) == test.nhigh, 'invalid') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment