# question about what this line might be trying to accomplish

• 03-21-2003
Silvercord
question about what this line might be trying to accomplish
I'm not entirely sure about this line of code, its from the original gl quake's source code. Carmack does a lot of funny things at the bit level and I have no friggin clue what they are supposed to be

the actual part of this is the
rand()&3) & 1

the entire context is this:
any clue what the bitwise and operator is being used for? If i remember correctly if bit A and bit B are 1, then the resulting bit is also a 1, otherwise its a zero if either are 0?
Code:

```        if ( ((rand()&3) & 1) ||  abs(deltay)>abs(deltax))         {                 tdir=d[1];                 d[1]=d[2];                 d[2]=tdir;         }```
Oh and this is actually monster code, I guess it randomly chooses a dijrection to move in somehow?

Thanks if you can help explain this to me :)

EDIT: is doing operations on variables faster on the bit level?
• 03-21-2003
Magos
Quote:

((rand()&3) & 1)
Why would he do that? That's the same as (rand() & 1). maybe he isn't so almighty as we first thought... :confused: :p

Anyway, I'd guess that rand() snippet creates a random True/False statement with a 50/50 chance for each.
What the whole part is doing i have no clue. Swaps two values when something occurs.
• 03-21-2003
Silvercord
so all rand() does is produce true/false? I honestly did not know that. I never understood how rand()%upperbound works. Like rand()%20 creates a random number to 20. I know what the modulus operator does but it still doesn't make sense completely.
• 03-21-2003
Silvercord
//rand() produces true/false with 50/50 chance of each
//& bitwise operator produces 1 when A bit AND B bit are 1, otherwise it is 0
//11 is binary for 3
//01/00 & 11 -> 01/00
//01&01 -> 01
//00&01 -> 00

that still doesn't make sense in terms of any useful functionality :(
• 03-21-2003
Perspective
what he is doing is masking out the 0 bit (in a bad way as magos pointed out since ((rand()&3) & 1) is the same as (rand() & 1) )
he might be using it because mod or floating point division can be expensive operations.
• 03-22-2003
Magos
Quote:

Originally posted by Silvercord
so all rand() does is produce true/false? I honestly did not know that. I never understood how rand()%upperbound works. Like rand()%20 creates a random number to 20. I know what the modulus operator does but it still doesn't make sense completely.
I didn't say rand(), I said rand() snippet, and by that I refered to the code you posted.
• 03-22-2003
Silvercord
What other languages allow you to manipulate bits directly/one at a time?
• 03-22-2003
Perspective
Quote:

Originally posted by Silvercord
What other languages allow you to manipulate bits directly/one at a time?
c, c++, java, and probably many more have bitwise operators such as...

&, |, ~, ^