Hello World!
im trying to make a bit cycling function with the following code
function rcycle(number, disp)
local len = math.ceil(math.log(number, 2))
return bit32.replace(bit32.rshift(number, disp), bit32.extract(number, length - disp, disp), 0, disp)
end
Goal:
rcycle(0b101001, 1) -> 0b110100
rcycle(0b101001, 2) -> 0b011010
etc.
my issue is that after rshifting the original number, the zeros in front get deleted, shifting everything else to the left to account for the empty space
like so
bit32.rshift(0b101001, 2)
-> 0b001010
->0b1010 --the zeros disappearing is the root of the issue
--lets see what happens if i cycle
rcycle(0b101001, 2)
-> bit32.replace(0b001010, 0b01, 0, 2) --this means the replace the first 2 bits of 001010 with 01, so it should give 011010 right? no
-> bit32.replace(0b1010, 0b1, 0, 2) --uh oh the âunnecessaryâ zeros got removed
-> 0b110
-> 5 --the intended result was 0b011010 (or 0b11010) which is equal to 26
Youâre right, lshift and rshift fill empty âvacantâ fields with 0.
print(bit32.lshift(0b101001, 2)) --> 10100100 (164 in decimal)
print(bit32.rshift(0b101001, 2)) --> 001010 (respectively 1010; 10 in decimal)
The leading zeros in 0b001010 may be omitted (0b1010). The number still consists of 32 bits (single precision floating point), but all those repeating numbers arenât output for better readability.
There was a slight error in extracting and replacing because positioning is done right to left and starting with 0.
local function rcycle(number: number, disp: number): number
local len = math.ceil(math.log(number, 2))
disp = math.max(math.round(disp), 1) % len
local rshifted = bit32.rshift(number, disp)
return bit32.replace(
rshifted, bit32.extract(number, 0, disp), len - disp, disp
)
end
print(rcycle(0b101001, 2)) --> 26 (0b11010 respectively 0b0011010)
Side note: disp must be a positive integer and not higher than the length. Using modulus we get the correct disposition from higher numbers (e.g. 7 â 1; len = 6).