Handy-Dandy Computer Math Tricks

Credits: I am heavily influenced by the book Algorithms (Sedgewick 1983). IMHO, that book really formed the way I learned to program.

Disclaimer 1: These tricks have probably been discovered elsewhere, I have done no research to find out, they're just things I discovered or hacked together at various times.

Disclaimer 2: I made up all of this stuff over the course of a day, not peeking at anyone else's code. These tricks are just that, tricks. They work as far as I know (and I've done some REASONABLE testing to make sure) but there may be a typo below, or some other machine-specific thing I overlooked, so I make no guarantees.

Mapping a hex digit to its binary equivalent

Goal: Given a character in the set "0123456789abcdefABCDEF" map it to the binary value 0-15 associated with that hex digit.

Example: Accept 'd' or 'D' and return 13

Converting 4 ascii binary digits to their equivalent value

Goal: Accept a string of 4 characters that are '0' or '1', and return the binary value that string represents.

Example: Accept "0101" and return 5

Is only one bit set?

Goal: Return a flag indicating that whether there one, or 0-or-many bits set in a given number. This is sometimes useful in networking code.

Example: Accept 1024 or 1048576 and return 1. Accept 0 or 17 and return 0.


Back to minutia page