Skip to main content
Mod Removes Wiki by Doorknob
n used for two different numbers, changed one to m
Source Link
flornquake
  • 1.6k
  • 11
  • 26

Use bitwise operations for checking numbers between 0 and any 2n-1

Might be a bit of an edge case, but it could come in handy sometimes. It relies on the fact that all numbers to which 2m=2n-1 applies have the rightmost n bits set to 1.

So, 710 == 000001112, 1510 == 000011112, 3110 == 000111112 and so on.

The trick is x&~nx&~m. This will return true whenever x is not between 0 and nm (inclusive), and false otherwise. It saves 6 bytes from the next shortest equivalent expression: x>=0&&x<=nx>=0&&x<=m, but obviously only works when nm satisfies 2n-1.

Use bitwise operations for checking numbers between 0 and any 2n-1

Might be a bit of an edge case, but it could come in handy sometimes. It relies on the fact that all numbers to which 2n-1 applies have the rightmost n bits set to 1.

So, 710 == 000001112, 1510 == 000011112, 3110 == 000111112 and so on.

The trick is x&~n. This will return true whenever x is not between 0 and n (inclusive), and false otherwise. It saves 6 bytes from the next shortest equivalent expression: x>=0&&x<=n, but obviously only works when n satisfies 2n-1.

Use bitwise operations for checking numbers between 0 and any 2n-1

Might be a bit of an edge case, but it could come in handy sometimes. It relies on the fact that all numbers to which m=2n-1 applies have the rightmost n bits set to 1.

So, 710 == 000001112, 1510 == 000011112, 3110 == 000111112 and so on.

The trick is x&~m. This will return true whenever x is not between 0 and m (inclusive), and false otherwise. It saves 6 bytes from the next shortest equivalent expression: x>=0&&x<=m, but obviously only works when m satisfies 2n-1.

Source Link
Sean Latham
  • 1.4k
  • 11
  • 20

Use bitwise operations for checking numbers between 0 and any 2n-1

Might be a bit of an edge case, but it could come in handy sometimes. It relies on the fact that all numbers to which 2n-1 applies have the rightmost n bits set to 1.

So, 710 == 000001112, 1510 == 000011112, 3110 == 000111112 and so on.

The trick is x&~n. This will return true whenever x is not between 0 and n (inclusive), and false otherwise. It saves 6 bytes from the next shortest equivalent expression: x>=0&&x<=n, but obviously only works when n satisfies 2n-1.