user2749903
user2749903

Reputation: 1305

Check if number can be divided by 16

How can i check if a 32 bit integer is a multiply of 16 only using bit operators? I know that the theory is to use bitshift to right by 4 could anyone explain why is following expression true?

boolean b = 16 >> 4 == 17 >> 4;

Upvotes: 0

Views: 526

Answers (1)

BeyelerStudios
BeyelerStudios

Reputation: 4283

x & 0x0F is going to be 0 for numbers dividable by 16 (0x10)

bool div16 = (x & 0x0F) == 0;

If you want to check this with bit shifts: first shift out the four bits, then shift back in zeros

bool div16 = x == (x >> 4) << 4;

Upvotes: 1

Related Questions