zoukankan      html  css  js  c++  java
  • C 编程技巧

    1. /* round up for aligment */

    #define round_up(x, aligment) (x) + ((aligment) - 1) ) / (aligment) ) * (aligment) )

    round_up(7, 5) = 10

    2.  取负数,再进行模运算   (-7 % 5 = 3  ->  7 加上 3 就可以被 5 整除)(整数A最少加上多少就可以被整数B整除)

    void *
    memcpy (dstpp, srcpp, len)
         void *dstpp;
         const void *srcpp;
         size_t len;
    {
      unsigned long int dstp = (long int) dstpp;
      unsigned long int srcp = (long int) srcpp;
    
      /* Copy from the beginning to the end.  */
    
      /* If there not too few bytes to copy, use word copy.  */
      if (len >= OP_T_THRES)
        {   
          /* Copy just a few bytes to make DSTP aligned.  */
          len -= (-dstp) % OPSIZ;
          BYTE_COPY_FWD (dstp, srcp, (-dstp) % OPSIZ);
    ...
    
    }

    3. list_entry 

    #define list_entry(ptr, type, member)  (type *) (char *)(ptr) - (unsigned long) &((type *)0)->member ) ) 
    从一个结构体的成员指针找到其容器的指针
    把0强制转化为指针类型,即0是一个地址,为段基址。以0为结构体的基址,再取结构体的成员member的地址,那么这个地址就等于成员member到结构体基地址的偏移字节数。
    #define list_entry(ptr, type, member)  container_of(ptr, type, member)
    #define
    container_of(ptr, type, member) ({ const typeof( ((type *)0)->member ) *__mptr = (ptr); (type *)( (char *)__mptr - offsetof(type,member) );})
    #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

     

    4. 获取一个数组的元素个数

    #define SIZE_ARRAY(a)  ( sizeof((a)) / sizeof((a[0])) )

    5. 十六进制转换成整数

    #define hexdigit(x)   (((x) <= '9') ? 'x' - '0' : ((x) & 7 ) + 9 )

    6. 大小写转换

    c &= 0xDF;  //小写字母转换成大写字母 

    c |= 0x20;   //大写字母转换成小写字

  • 相关阅读:
    【笔记】Maven使用入门
    【笔记】c++文件
    【笔记】IntelliJ IDEA配置Hibernate
    【HTML5校企公益课】第四天
    【c++习题】【17/4/16】动态分配内存
    C#
    C#
    C#
    C#
    C#
  • 原文地址:https://www.cnblogs.com/xiaokuang/p/4612669.html
Copyright © 2011-2022 走看看