[Math] Binary logarithm, part II


How to check if a value has no more than 15 bits?

assert (val <= 0x7fff);
// or:
assert (val < 0x8000);

Nooo! How disgusting! Let's try better:

assert (val < (1<<15));

Binary logarithm of 1<<15 is 15.

This is a real piece of code I'm working right now on.

        assert (vals[0] < (1<<15));
        assert (vals[1] < (1<<10));
        assert (vals[2] < (1<<10));
        assert (vals[3] < (1<<8));
        assert (vals[4] < (1<<9));

vals[0] must be under 15 bits, vals[1] and 2 -- under 10 bits, etc. This is way better for self-documenting purposes than 0x7fff, 0x8000, 0x3fff, 0x4000, etc.

See also.

(the post first published at 20221005.)

List of my other blog posts.

Subscribe to my news feed

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.