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

Bit Handling

Started by ZephyrWolf_, 22 October 2015 - 01:51 AM
ZephyrWolf_ #1
Posted 22 October 2015 - 03:51 AM
Im writting a rights system, where each registered player is given a number, where each bit corresponds with access to something, lets say a door for example. (Its vauge because im making it so i can be applied to anything.) I have written this system before but not in lua.

I am having problem with the removeRight method. What it is supposed to do, is set the specified bit of a number to zero, everytime.

my original though was to do

bit32.band(playerRight, bit32.bnot(bitLocation))

but its not working as I want.

eg

1011, removeRight at index 0 yeilds = 1010

I would love to hear all help, and if you have any questions let me know, I am happy to elaborate if I wasn't clear enough
safetyscissors #2
Posted 22 October 2015 - 09:48 AM
Hmm interesting problem.

I'd suggest

newRights = bit.bxor(playerRight, math.pow(2, bitLocation))
--# check that permission was originally false and we just toggled it on.
if newRights > oldRights then
  newRights = oldRights.
end

given playerRight = 1011, bitLocation = 0
then math.pow(2, 0) is 1
so xor(1011, 1) returns 1010

given playerRight = 1011, bitLocation = 3
then math.pow(2,0) is 1000
so xor(1011, 1000) returns 0011

Problem case,
given playerRight = 1011, bitLocation = 2
then math.pow(2,2) is 0100
so xor(1011,0100) returns 1111
but 1111 is > original playerRight. and can be corrected.
Bomb Bloke #3
Posted 22 October 2015 - 10:20 AM
bit32.band(playerRight, bit32.bnot(bitLocation))

This'd be correct if it used 2^bitLocation instead of just bitLocation, but bnot's a bit broke under CC 1.74. I'm not sure how many other functions in the API are experiencing issues, but safetyscissors's code looks like it'd do the trick so long as bxor's ok.
ZephyrWolf_ #4
Posted 24 October 2015 - 11:59 AM
yeah it looks like it thanks alot, it late so ill test it tomoz. also bomb bloke, i did have it to the power i just made a type in this post, sorry, but yeah as you said it didnt work. But yeah safteysissor's code looks good, so thankyou all ^_^/>