Recently in reading C language book, feel also quite interesting, a bit of harvest, collected a few beautiful small procedures, with the grand total reward!
1) Replace the 10 binary number with the small function of any binary number
Char *baseconv (unsigned int num, int base) { static char retbuf[33]; char *p; if (Base < 2 | | Base >) return NULL; p = &retbuf[sizeof (RETBUF)-1]; *p = ' + '; do{ *--p = "0123456789abcdef" [num% base]; Num/= base; } while (num! = 0); return p;}
"ABCdef" [5] can be understood as
Char *p = "abcdef"; ... p[5] ...
Arrays and subscripts are interchangeable in the C language, so they can also be written as 5["abcdef" (not advocating ha, for reasons you know)
2) calculates the number of bits in an unsigned integer as 1
static int bittab[] = { 0,1,1,2, 1,2,2,3, 1,2,2,3, 2,3,3,4};int bitcount (unsigned int u) { int n = 0; for (; U! = 0; u >>= 4) n + = bittab[u & 0x0f]; return n;}
There's nothing to introduce about the bitwise operation, so let's think about the structure of Bittab.
3) Encapsulation of the free function
void Saferfree (void **pp) { if (pp! = null && *PP! = null) {free (*PP); *PP = NULL;} } #define SAFEFREE (P) saferfree ((void**) & (P))
The free function does not check if the incoming pointer is null, nor does it set the pointer to null before returning. It's a good habit to set it to null after releasing the pointer.
C Language Small Program