language agnostic - One-liner for checking if integer is of form 2^1-2^j using bitwise operators -


i want 1 line code check whether given integer of form 2i - 2j or not. (using bitwise operators)

as andreyt says, answer can found in hacker's delight:

use following formula turn off rightmost contiguous string of 1-bits (e.g., 01011000 ⇒ 01000000):

((x | (x – 1)) + 1) & x 

this may used see if nonnegative integer of form 2j – 2k jk ≥ 0; apply formula followed 0-test of result.

(was debating whether post this, it's homework question, andreyt mentioned , it's googlable, figure it's more helpful quote directly; i'll let questioner deal ethical implications of accepting on homework, , expect if answer depends on this, write explanation of how works himself)


Comments

Popular posts from this blog

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -

openssl - Load PKCS#8 binary key into Ruby -