Bitwise operator >> and &

I'm trying to understand a bit of code here:

1
2
3
4
5
6
7
8
9
10
11
12
13
(...)
#define MAX_UNSIGNED_SHORT                  (0xffff)

#define RANDOM_A      (1103515245)
#define RANDOM_C      (12345)
#define RANDOM_SHIFT  (16)

m_ulRandomSeed = ((RANDOM_A * m_ulRandomSeed) + RANDOM_C);

unsigned short us = ((unsigned short)((((m_ulRandomSeed >> RANDOM_SHIFT) & MAX_UNSIGNED_SHORT) * ((unsigned long)usNum)) / (MAX_UNSIGNED_SHORT + 1)));

return us;
}

I think I understand that m_ulRandomSeed >> RANDOM_SHIFT is the equivalent of dividing m_ulRandomSeed by 2^16. Is this right? I'm also wondering about the purpose of "comparing" m_ulRandomSeed with MAX_UNSIGNED_SHORT using &, and what it would result in... can you help me out? Thanks!

Maxime Bonin-Francoeur
Last edited on

2^16. Is this right?
Yes.
65536>>16 = 1 or 65536/2^16 = 1

I'm also wondering about the purpose of ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
unsigned short us = 
(
(unsigned short)
  (
    (
      (
         (m_ulRandomSeed >> RANDOM_SHIFT) & MAX_UNSIGNED_SHORT   // Note 1
      ) 
      * 
      (
          (unsigned long)usNum
      )
    ) 
    / 
    (
      MAX_UNSIGNED_SHORT + 1
    )
  )
);


Note 1: The & is just making sure that the result from m_ulRandomSeed >> RANDOM_SHIFT is NO greater than 16-bits.
It is a bit-wise AND(&) not logical AND(&&).
1
2
3
4
5
6
7
0x5 in binary is 0101
 &               &&&&
0x4 in binary is 0100
_____________________
                 0100
Therefore 0x5 & 0x4 = 0x4(bit-wise), 
0x5 && 0x4 = true(logic).

So, if the value of m_ulRandomSeed >> RANDOM_SHIFT was 0x54321
1
2
3
4
5
0x54321 -> 01010100001100100001
&          &&&&&&&&&&&&&&&&&&&&
0xffff  -> 00001111111111111111
_______________________________
0x04321 -> 00000100001100100001
I forgot the following line:
1
2
(...)
unsigned long m_ulRandomSeed;

But how can m_ulRandomSeed be greater than 0xffff if it's already been divided by 2^16 and is an unsigned long? :-) But I get the picture thanks a lot!
I think you are right, it can't.
Topic archived. No new replies allowed.