This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Griffith's profile picture

BitShift/Cycle Question

Started by Griffith, 22 November 2015 - 02:16 AM
Griffith #1
Posted 22 November 2015 - 03:16 AM
I am trying to use a bitshift to cycle the bits. not sure what the proper term for this is but example is 10001000 shifted twice to the left becomes 00100010. I am probably over complicating how to do this but last time i tried to do this it was a function built into the language. Any guidance would be greatly appreciated as I keep hitting a wall with everything I try and at this point am feeling a little burned as there is probably some simple bitmath that will do this but it is a relatively new thing to me so I figured I would ask for pointers.

Thanks for any help.
Bomb Bloke #2
Posted 22 November 2015 - 03:27 AM
You're after the functions in the bit API.

Edit:

Actually testing it, I see certain CC 1.74 bugs don't make that process as easy as it should be; at least, not if you want to cycle the full 32bits.

And it sounds like you only want to do 8. Hence you might just do this:

local val = 136  -- 0b10001000

local shiftTimes = 2

for i = 1, shiftTimes do
  val = val * 2
  if val > 255 then val = val - 255 end
end

Right-shifting can be performed in much the same manner:

local val = 136  -- 0b10001000

local shiftTimes = 2

for i = 1, shiftTimes do
  val = val / 2
  if val ~= math.floor(val) then val = val + 127.5 end
end
Edited on 22 November 2015 - 02:45 AM
Griffith #3
Posted 22 November 2015 - 04:16 AM
You're after the functions in the bit API.

I figured it out and I knew I was looking for the bit API I just for the life of be could not get my brain to do the math needed.

blshift and band did the trick for what I wanted…not sure if this is the proper way to do it but it works so i am happy.