diff --git a/lua.lyx b/lua.lyx index 975f2598..923ee037 100644 --- a/lua.lyx +++ b/lua.lyx @@ -4930,6 +4930,50 @@ Multiply 32-bit numbers and . bits. \end_layout +\begin_layout Subsection +bit.fextract: Extract bit field +\end_layout + +\begin_layout Itemize +Syntax: number bit.fextract(number value, number shift, number width) +\end_layout + +\begin_layout Standard +Extract bits starting from bit from number . + This is more compact way to write +\begin_inset Formula $\left(value\gg shift\right)\&\left(2^{width}-1\right)$ +\end_inset + +. +\end_layout + +\begin_layout Subsection +bit.bfields: Split number into bit fields +\end_layout + +\begin_layout Itemize +Syntax: number... + bit.bfields(number v, number q...) +\end_layout + +\begin_layout Standard +Split a number into bitfields of bits (in order, from least significant + towards more significant bits), with no padding in between. +\end_layout + +\begin_layout Itemize +Eg. + number of form 0 bbbbb ggggg rrrrr can be decoded to its component fields + using r,g,b = bit.bfields(v, 5, 5, 5). + +\end_layout + +\begin_layout Itemize +Eg. + number of form x yyyyyyy w zzzzzzz can be decode to its component fields + using z, w, y, x = bit.bfields(v, 7, 1, 7, 1). +\end_layout + \begin_layout Standard \begin_inset Newpage pagebreak \end_inset diff --git a/lua.pdf b/lua.pdf index ce360640..e2c89a85 100644 Binary files a/lua.pdf and b/lua.pdf differ diff --git a/src/lua/bit.cpp b/src/lua/bit.cpp index 1edf4be4..8c38e7d6 100644 --- a/src/lua/bit.cpp +++ b/src/lua/bit.cpp @@ -358,6 +358,40 @@ namespace return 2; } + int bit_fextract(lua::state& L, lua::parameters& P) + { + uint64_t a, b, c; + + P(a, b, c); + if(b > 63) + L.pushnumber(0); + else if(c > 63) + L.pushnumber(a >> b); + else + L.pushnumber((a >> b) & ((1 << c) - 1)); + return 1; + } + + int bit_bfields(lua::state& L, lua::parameters& P) + { + uint64_t v; + unsigned values = L.gettop(); + + P(v); + for(unsigned i = 1; i < values; i++) { + uint64_t q; + P(q); + if(q > 63) { + L.pushnumber(v); + v = 0; + } else { + L.pushnumber(v & ((1 << q) - 1)); + v >>= q; + } + } + return values - 1; + } + lua::functions LUA_bitops_fn(lua_func_bit, "bit", { {"flagdecode", flagdecode_core}, {"rflagdecode", flagdecode_core}, @@ -412,6 +446,8 @@ namespace {"quotent", bit_quotent}, {"multidiv", bit_multidiv}, {"mul32", bit_mul32}, + {"fextract", bit_fextract}, + {"bfields", bit_bfields}, {"binary_ld_u8be", bit_ldbinarynumber}, {"binary_ld_s8be", bit_ldbinarynumber}, {"binary_ld_u16be", bit_ldbinarynumber},