robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3e93793bb1
master
1*lua-bit.txt* Nvim 2 3Lua BitOp *lua-bit* 4 5Adapted from https://bitop.luajit.org. 6 7Lua BitOp is a C extension module for Lua 5.1/5.2 which adds bitwise 8operations on numbers. 9 10 Type |gO| to see the table of contents. 11 12============================================================================== 13API FUNCTIONS *lua-bit-api* 14 15This list of API functions is not intended to replace a tutorial. If you are 16not familiar with the terms used, you may want to study the Wikipedia article 17on bitwise operations (https://en.wikipedia.org/wiki/Bitwise_operation) first. 18 19------------------------------------------------------------------------------ 20Loading the BitOp module 21 *lua-bit-module* 22 23The suggested way to use the BitOp module is to add the following to the start 24of every Lua file that needs one of its functions: >lua 25 local bit = require("bit") 26< 27This makes the dependency explicit, limits the scope to the current file and 28provides faster access to the bit.* functions, too. It's good programming 29practice not to rely on the global variable bit being set (assuming some other 30part of your application has already loaded the module). The require function 31ensures the module is only loaded once, in any case. 32 33------------------------------------------------------------------------------ 34Defining Shortcuts 35 *lua-bit-shortcuts* 36 37It's a common (but not a required) practice to cache often used module 38functions in locals. This serves as a shortcut to save some typing and also 39speeds up resolving them (only relevant if called hundreds of thousands of 40times). 41>lua 42 local bnot = bit.bnot 43 local band, bor, bxor = bit.band, bit.bor, bit.bxor 44 local lshift, rshift, rol = bit.lshift, bit.rshift, bit.rol 45 -- etc... 46 47 -- Example use of the shortcuts: 48 local function tr_i(a, b, c, d, x, s) 49 return rol(bxor(c, bor(b, bnot(d))) + a + x, s) + b 50 end 51< 52 53Remember that `and`, `or` and `not` are reserved keywords in Lua. They cannot 54be used for variable names or literal field names. That's why the 55corresponding bitwise functions have been named `band`, `bor`, and `bnot` (and 56`bxor` for consistency). 57 58While we are at it: a common pitfall is to use bit as the name of a local 59temporary variable — well, don't! :-) 60 61------------------------------------------------------------------------------ 62About the Examples 63 64The examples below show small Lua one-liners. Their expected output is shown 65after `-->`. This is interpreted as a comment marker by Lua so you can cut & 66paste the whole line to a Lua prompt and experiment with it. 67 68Note that all bit operations return signed 32 bit numbers (rationale). And 69these print as signed decimal numbers by default. 70 71For clarity the examples assume the definition of a helper function 72`printx()`. This prints its argument as an unsigned 32 bit hexadecimal number 73on all platforms: 74>lua 75 function printx(x) 76 print("0x"..bit.tohex(x)) 77 end 78< 79------------------------------------------------------------------------------ 80Bit operations 81 *lua-bitop* 82 83bit.tobit({x}) *bit.tobit()* 84 Normalizes a number to the numeric range for bit operations and returns 85 it. This function is usually not needed since all bit operations already 86 normalize all of their input arguments. See |lua-bit-semantics|. 87 88 Example: >lua 89 print(0xffffffff) --> 4294967295 (see Note) 90 print(bit.tobit(0xffffffff)) --> -1 91 printx(bit.tobit(0xffffffff)) --> 0xffffffff 92 print(bit.tobit(0xffffffff + 1)) --> 0 93 print(bit.tobit(2^40 + 1234)) --> 1234 94< 95 Note: |lua-bit-hex-literals| explains why the numbers printed in the first 96 two lines differ (if your Lua installation uses a double number type). 97 98bit.tohex({x} [, {n}]) *bit.tohex()* 99 Converts its first argument to a hex string. The number of hex digits is 100 given by the absolute value of the optional second argument. Positive 101 numbers between 1 and 8 generate lowercase hex digits. Negative numbers 102 generate uppercase hex digits. Only the least-significant `4*|n|` bits are 103 used. The default is to generate 8 lowercase hex digits. 104 105 Example: >lua 106 print(bit.tohex(1)) --> 00000001 107 print(bit.tohex(-1)) --> ffffffff 108 print(bit.tohex(0xffffffff)) --> ffffffff 109 print(bit.tohex(-1, -8)) --> FFFFFFFF 110 print(bit.tohex(0x21, 4)) --> 0021 111 print(bit.tohex(0x87654321, 4)) --> 4321 112< 113bit.bnot({x}) *bit.bnot()* 114 Returns the bitwise `not` of its argument. 115 116 Example: >lua 117 print(bit.bnot(0)) --> -1 118 printx(bit.bnot(0)) --> 0xffffffff 119 print(bit.bnot(-1)) --> 0 120 print(bit.bnot(0xffffffff)) --> 0 121 printx(bit.bnot(0x12345678)) --> 0xedcba987 122< 123bit.bor({...}) *bit.bor()* 124bit.band({...}) *bit.band()* 125bit.bxor({...}) *bit.bxor()* 126 Returns either the bitwise `or`, bitwise `and`, or bitwise `xor` of all of 127 its arguments. Note that more than two arguments are allowed. 128 129 Example: >lua 130 print(bit.bor(1, 2, 4, 8)) --> 15 131 printx(bit.band(0x12345678, 0xff)) --> 0x00000078 132 printx(bit.bxor(0xa5a5f0f0, 0xaa55ff00)) --> 0x0ff00ff0 133< 134bit.lshift({x}, {n}) *bit.lshift()* 135bit.rshift{(x}, {n}) *bit.rshift()* 136bit.arshift{(x}, {n}) *bit.arshift()* 137 Returns either the bitwise `logical left-shift`, bitwise `logical` 138 `right-shift`, or bitwise `arithmetic right-shift` of its first argument 139 by the number of bits given by the second argument. 140 141 Logical shifts treat the first argument as an unsigned number and shift in 142 0-bits. Arithmetic right-shift treats the most-significant bit as a sign 143 bit and replicates it. Only the lower 5 bits of the shift count are used 144 (reduces to the range [0..31]). 145 146 Example: >lua 147 print(bit.lshift(1, 0)) --> 1 148 print(bit.lshift(1, 8)) --> 256 149 print(bit.lshift(1, 40)) --> 256 150 print(bit.rshift(256, 8)) --> 1 151 print(bit.rshift(-256, 8)) --> 16777215 152 print(bit.arshift(256, 8)) --> 1 153 print(bit.arshift(-256, 8)) --> -1 154 printx(bit.lshift(0x87654321, 12)) --> 0x54321000 155 printx(bit.rshift(0x87654321, 12)) --> 0x00087654 156 printx(bit.arshift(0x87654321, 12)) --> 0xfff87654 157< 158bit.rol({x}, {n}) *bit.rol()* 159bit.ror({x}, {n}) *bit.ror()* 160 Returns either the bitwise `left rotation`, or bitwise `right rotation` of 161 its first argument by the number of bits given by the second argument. 162 Bits shifted out on one side are shifted back in on the other side. 163 164 Only the lower 5 bits of the rotate count are used (reduces to the range 165 [0..31]). 166 167 Example: >lua 168 printx(bit.rol(0x12345678, 12)) --> 0x45678123 169 printx(bit.ror(0x12345678, 12)) --> 0x67812345 170< 171bit.bswap({x}) *bit.bswap()* 172 Swaps the bytes of its argument and returns it. This can be used to 173 convert little-endian 32 bit numbers to big-endian 32 bit numbers or vice 174 versa. 175 176 Example: >lua 177 printx(bit.bswap(0x12345678)) --> 0x78563412 178 printx(bit.bswap(0x78563412)) --> 0x12345678 179< 180------------------------------------------------------------------------------ 181Example Program 182 183This is an implementation of the (naïve) Sieve of Eratosthenes algorithm. It 184counts the number of primes up to some maximum number. 185 186A Lua table is used to hold a bit-vector. Every array index has 32 bits of the 187vector. Bitwise operations are used to access and modify them. Note that the 188shift counts don't need to be masked since this is already done by the BitOp 189shift and rotate functions. 190>lua 191 local bit = require("bit") 192 local band, bxor = bit.band, bit.bxor 193 local rshift, rol = bit.rshift, bit.rol 194 195 local m = tonumber(arg and arg[1]) or 100000 196 if m < 2 then m = 2 end 197 local count = 0 198 local p = {} 199 200 for i=0,(m+31)/32 do p[i] = -1 end 201 202 for i=2,m do 203 if band(rshift(p[rshift(i, 5)], i), 1) ~= 0 then 204 count = count + 1 205 for j=i+i,m,i do 206 local jx = rshift(j, 5) 207 p[jx] = band(p[jx], rol(-2, j)) 208 end 209 end 210 end 211 212 io.write(string.format("Found %d primes up to %d\n", count, m)) 213< 214Lua BitOp is quite fast. This program runs in less than 90 milliseconds on a 3 215GHz CPU with a standard Lua installation, but performs more than a million 216calls to bitwise functions. If you're looking for even more speed, check out 217|lua-luajit|. 218 219------------------------------------------------------------------------------ 220Caveats *lua-bit-caveats* 221 222Signed Results ~ 223 224Returning signed numbers from bitwise operations may be surprising to 225programmers coming from other programming languages which have both signed and 226unsigned types. But as long as you treat the results of bitwise operations 227uniformly everywhere, this shouldn't cause any problems. 228 229Preferably format results with `bit.tohex` if you want a reliable unsigned 230string representation. Avoid the `"%x"` or `"%u"` formats for `string.format`. 231They fail on some architectures for negative numbers and can return more than 2328 hex digits on others. 233 234You may also want to avoid the default number to string coercion, since this 235is a signed conversion. The coercion is used for string concatenation and all 236standard library functions which accept string arguments (such as `print()` or 237`io.write()`). 238 239Conditionals ~ 240 241If you're transcribing some code from C/C++, watch out for bit operations in 242conditionals. In C/C++ any non-zero value is implicitly considered as `true`. 243E.g. this C code: >c 244 if (x & 3) ... 245< 246must not be turned into this Lua code: >lua 247 if band(x, 3) then ... -- wrong! 248< 249In Lua all objects except `nil` and `false` are considered `true`. This 250includes all numbers. An explicit comparison against zero is required in this 251case: >lua 252 if band(x, 3) ~= 0 then ... -- correct! 253 254Comparing Against Hex Literals ~ 255 256Comparing the results of bitwise operations (signed numbers) against hex 257literals (unsigned numbers) needs some additional care. The following 258conditional expression may or may not work right, depending on the platform 259you run it on: >lua 260 bit.bor(x, 1) == 0xffffffff 261< 262E.g. it's never true on a Lua installation with the default number type. Some 263simple solutions: 264 265 Never use hex literals larger than 0x7fffffff in comparisons: >lua 266 bit.bor(x, 1) == -1 267< 268 Or convert them with bit.tobit() before comparing: >lua 269 bit.bor(x, 1) == bit.tobit(0xffffffff) 270< 271 Or use a generic workaround with bit.bxor(): >lua 272 bit.bxor(bit.bor(x, 1), 0xffffffff) == 0 273< 274 Or use a case-specific workaround: >lua 275 bit.rshift(x, 1) == 0x7fffffff 276< 277============================================================================== 278OPERATIONAL SEMANTICS AND RATIONALE *lua-bit-semantics* 279 280 281Input and Output Ranges ~ 282 *lua-bit-io-ranges* 283 284Bitwise operations cannot sensibly be applied to FP numbers (or their 285underlying bit patterns). They must be converted to integers before operating 286on them and then back to FP numbers. 287 288It's desirable to define semantics that work the same across all platforms. 289This dictates that all operations are based on the common denominator of 32 290bit integers. The `float` type provides only 24 bits of precision. This makes 291it unsuitable for use in bitwise operations. Lua BitOp refuses to compile 292against a Lua installation with this number type. 293 294Bit operations only deal with the underlying bit patterns and generally ignore 295signedness (except for arithmetic right-shift). They are commonly displayed 296and treated like unsigned numbers, though. 297 298But the Lua number type must be signed and may be limited to 32 bits. Defining 299the result type as an unsigned number would not be cross-platform safe. All 300bit operations are thus defined to return results in the range of signed 32 301bit numbers (converted to the Lua number type). 302 303 *lua-bit-hex-literals* 304Hexadecimal literals are treated as unsigned numbers by the Lua parser before 305converting them to the Lua number type. This means they can be out of the 306range of signed 32 bit integers if the Lua number type has a greater range. 307E.g. 0xffffffff has a value of 4294967295 in the default installation, but may 308be -1 on embedded systems. It's highly desirable that hex literals are treated 309uniformly across systems when used in bitwise operations. All bit operations 310accept arguments in the signed or the unsigned 32 bit range (and more, see 311below). Numbers with the same underlying bit pattern are treated the same by 312all operations. 313 314 315Modular Arithmetic ~ 316 *lua-bit-modular-arith* 317 318Arithmetic operations on n-bit integers are usually based on the rules of 319modular arithmetic modulo 2^n. Numbers wrap around when the mathematical 320result of operations is outside their defined range. This simplifies hardware 321implementations and some algorithms actually require this behavior (like many 322cryptographic functions). 323 324E.g. for 32 bit integers the following holds: `0xffffffff + 1 = 0` 325 326Arithmetic modulo 2^32 is trivially available if the Lua number type is a 32 327bit integer. Otherwise normalization steps must be inserted. Modular 328arithmetic should work the same across all platforms as far as possible: 329 330- For the default number type of double, arguments can be in the range of 331 ±2^51 and still be safely normalized across all platforms by taking their 332 least-significant 32 bits. The limit is derived from the way doubles are 333 converted to integers. 334- The function bit.tobit can be used to explicitly normalize numbers to 335 implement modular addition or subtraction. E.g. >lua 336 bit.tobit(0xffffffff + 1) 337 returns 0 on all platforms. 338- The limit on the argument range implies that modular multiplication is 339 usually restricted to multiplying already normalized numbers with small 340 constants. FP numbers are limited to 53 bits of precision, anyway. E.g. 341 (2^30+1)^2 does not return an odd number when computed with doubles. 342 343BTW: The `tr_i` function shown here |lua-bit-shortcuts| is one of the 344non-linear functions of the (flawed) MD5 cryptographic hash and relies on 345modular arithmetic for correct operation. The result is fed back to other 346bitwise operations (not shown) and does not need to be normalized until the 347last step. 348 349 350Restricted and undefined behaviors ~ 351 *lua-bit-restrictions* 352 353The following rules are intended to give a precise and useful definition (for 354the programmer), yet give the implementation (interpreter and compiler) the 355maximum flexibility and the freedom to apply advanced optimizations. It's 356strongly advised not to rely on undefined or implementation-defined behavior. 357 358- All kinds of floating-point numbers are acceptable to the bitwise 359 operations. None of them cause an error, but some may invoke undefined 360 behavior: 361 - `-0` is treated the same as `+0` on input and is never returned as a 362 result. 363 - Passing `±Inf`, `NaN` or numbers outside the range of `±2^51` as input 364 yields an undefined result. 365 - Non-integral numbers may be rounded or truncated in an 366 implementation-defined way. This means the result could differ between 367 different BitOp versions, different Lua VMs, on different platforms or 368 even between interpreted vs. compiled code (as in LuaJIT). Avoid passing 369 fractional numbers to bitwise functions. Use `math.floor()` or 370 `math.ceil()` to get defined behavior. 371- Lua provides auto-coercion of string arguments to numbers by default. This 372 behavior is deprecated for bitwise operations. 373 374============================================================================== 375COPYRIGHT 376 377Lua BitOp is Copyright (C) 2008-2025 Mike Pall. 378Lua BitOp is free software, released under the MIT license. 379 380 vim:tw=78:ts=4:sw=4:sts=4:et:ft=help:norl: