首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > C/C++ > 一些高效代码片断
【标  题】:一些高效代码片断
【关键字】:
【来  源】:http://www.cublog.cn/u/8780/showart.php?id=236882

一些高效代码片断

转自:http://www.fopen.org/bbs/redirect.php?fid=26&tid=4403&goto=nextoldset
 
一个快速开方的函数

/* 来至 Quake 3 的源码 */
float CarmSqrt(float x){
        union{
                int intPart;
                float floatPart;
        } convertor;
        union{
                int intPart;
                float floatPart;
        } convertor2;
        convertor.floatPart = x;
        convertor2.floatPart = x;
        convertor.intPart = 0x1FBCF800 + (convertor.intPart >> 1);
        convertor2.intPart = 0x5f3759df - (convertor2.intPart >> 1);
        return 0.5f*(convertor.floatPart + (x * convertor2.floatPart));
}

参考链接:http://greatsorcerer.go2.icpcn.com/info/fastsqrt.html

字符串 hash 函数

unsigned long hash(const char *name,size_t len)
{
        unsigned long h=(unsigned long)len;
        size_t step = (len>>5)+1;
        for (size_t i=len; i>=step; i-=step)
            h = h ^ ((h<<5)+(h>>2)+(unsigned long)name[i-1]);
        return h;
}

一个方便的 hash 函数应该散列的比较开,计算速度跟字符串长度关系不大,又不能只计算字符串的开头或末尾。这里的算法是从 Lua 中看来的。

快速 double 转整型

union luai_Cast { double l_d; long l_l; };
#define lua_number2int(i,d) \
        { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }

RGB565 的 alpha 混合

unsigned short alpha_blender(unsigned int x,unsigned int y,unsigned int alpha)
{
        x = (x | (x<<16)) & 0x7E0F81F;
        y = (y | (y<<16)) & 0x7E0F81F;
        unsigned int result = ((x - y) * alpha / 32 + y) & 0x7E0F81F;
        return (unsigned short)((result&0xFFFF) | (result>>16));
}

UTF8 到 UTF16 的转换(单个字符)


 

int UTF8toUTF16(int c)
{
        signed char *t=(signed char*)&c;
        int ret=*t &(0x0f | ((*t>>1) &0x1f) | ~(*t>>7));
        int i;
        assert ((*t & 0xc0) != 0x80);
        for (i=1;i<3;i++) {
                if ((t & 0xc0)!=0x80) {
                        break;
                }
                ret=ret<<6 | (t & 0x3f);
        }
        return ret;
}

out of shared memory segments:【上一篇】
boost库的常用组件的使用(ZT):【下一篇】
【相关文章】
没有相关文章
【随机文章】
  • 1 / 0 = ?
  • 续 IDT
  • 实战编译Linux内核
  • 发布一般应用程序
  • 卡巴6.0.1.411版本升级服务器(解决地震造成的不能升级问题)
  • ASP字数计算函数
  • asp.net的数据库连接数据示例
  • 二叉树的递归遍历
  • 快速安装中文Windows NT 4.0下的DOS工作站
  • 冒险岛吸怪教程
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 软讯网络 All Rigths Reserved.