Bit cycle function

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

any solutions or different ways of doing this?

I think I figured it out!

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).

1 Like

Thank you very much! :grin:
I hadn’t considered that rshift read from right to left so I appreciate you pointing that out.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.