operations with floating-point numbers.
left shifts correspond to multiplications by powers of two;
right shifts correspond to divisions.
However, bitwise-and and bitwise-or do not seem to have these translations.They are defined over the binary representation of integer numbers in base two.(也就是bitwise-and and bitwise-or 是在二进制整数下定义的操作)
It seems impossible to extend them in any meaningful way to floating-point numbers in general. Even some simple operations seem out of place. What should be the complement of 0.0? Should it be -1? Or 0xFFFFFFFF (which is 4294967295 in Lua, clearly different from -1)? Or maybe 2^64- 1 (a number that cannot be exactly represented in a double)?
e.g., by accepting more than 32 bits).
I will use hexadecimal notation for most examples in this chapter, to ease the
interpretation of the results. I will use the word MAX to represent the number
0xFFFFFFFF (that is, 2^32- 1). I will use also the following auxiliary function
throughout the examples:
function printx (x)
print(string.format("0x%X", x))
end
The bitwise library in Lua 5.2 is called bit32. This name makes it clear
that it operates over 32-bit numbers. Because and, or, and not are reserved
words in Lua, these operations are called respectively band, bor, and bnot. For
consistency, the exclusive-or operation is called bxor:
printx(bit32.band(0xDF, 0xFD)) --> 0xDD
printx(bit32.bor(0xD0, 0x0D)) --> 0xDD
printx(bit32.bxor(0xD0, 0xFF)) --> 0x2F
printx(bit32.bnot(0)) --> 0xFFFFFFFF
Functions band, bor, and bxor accept any number of arguments:
printx(bit32.bor(0xA, 0xA0, 0xA00)) --> 0xAAA
printx(bit32.band(0xFFA, 0xFAF, 0xAFF)) --> 0xAAA
printx(bit32.bxor(0, 0xAAA, 0)) --> 0xAAA
printx(bit32.bor()) --> 0x0
printx(bit32.band()) --> 0xFFFFFFFF
printx(bit32.bxor()) --> 0x0
(They are all commutative and associative.)
The bitwise library operates with unsigned integers. Its operations convert
any number given as an argument to an integer in the range 0–MAX. First,
non-integer numbers are rounded in a non-specified way. Second, numbers out
of the range 0–MAX are mapped into this range through a modulo operation:
the integer n becomes n%232. This operation is equivalent to getting the twocomplement
representation of the number and then taking the least 32 bits. As
expected, -1 becomes MAX. You can use the following operations to normalize a
number (that is, to map it into the range 0–MAX):
printx(bit32.bor(2^32)) --> 0x0
printx(bit32.band(-1)) --> 0xFFFFFFFF
Of course, in standard Lua it is easier to do n%(2^32)
...........to be continue