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.
Example: Accept 'd' or 'D' and return 13
int hexval(char c)
{
if (c <= '9') return (c - '0');
return (toupper(c) - 'A');
}
int hexval(char c)
{
static const char lookup[256] =
{ -1 ... 0, 1, 2, ... 10, 11, 12... 10, 11, 12... -1 ... }
return(lookup[c]);
}
int hexval(char c)
{
return ((((c & 0x3f) + 9) % 57) & 0x0f);
}
Example: Accept "0101" and return 5
int binval(char s[4])
{
int i;
int j;
for (i = j = 0; i < 4; ++i)
{
j = (j << 1) | s[i] & 1;
}
return (j);
}
int binval(char s[4])
{
return (
(s[3] & 0x01) |
((s[2] & 0x01) << 1) |
((s[1] & 0x01) << 2) |
((s[0] & 0x01) << 3));
}
int binval(char s[4])
{
return ((ntohl((*((long *)s)) % 127) % 17);
}
Example: Accept 1024 or 1048576 and return 1. Accept 0 or 17 and return 0.
int onebit (int n)
{
int i;
for (i = 1; i < 8 * sizeof(n); ++i)
{
if ((n ^ (1 << i)) == 0) return (1);
}
return (0);
}
int onebit (int n)
{
return (n &&
!((n & 0x0000ffff && n & 0xffff0000) ||
(n & 0x00ff00ff && n & 0xff00ff00) ||
(n & 0x0f0f0f0f && n & 0xf0f0f0f0) ||
(n & 0x33333333 && n & 0xcccccccc) ||
(n & 0x55555555 && n & 0xaaaaaaaa)));
}
int onebit (int n)
{
return (!(i & (i - 1)));
}