C Language Small Program

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.