代码片段(云风的blog)

一个快速开方的函数:

/* 来至 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));
}

参考链接:[External Link]http://greatsorcerer.go2.icpcn.com/info/fastsqrt.html


快速 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; }

参考链接: [InterWiki] double to int 神奇的 magic number

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));
}

参考链接: [InterWiki] 64K 色的 Alpha 混合

一个不错的字符串 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  中看来的。

关于脏矩形技术的演示 
由于代码过长,单起一页: 脏矩形 demo
参考链接: [InterWiki] Blog上的帖子:脏矩形演示demo

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[i] & 0xc0)!=0x80) {
			break;
		}
		ret=ret<<6 | (t[i] & 0x3f);
	}
	return ret;
}

这只是一个字符的转换,如果转换字符串,可以再做一点优化。

UTF-8/UTF-16 到 UTF-C 转换代码 
参考链接: [InterWiki] 一种对汉字更环保的 Unicode 编码方案

一个 32bit 整数,取不小于它的 2 的整数次幂 
static inline bool 
is_pow_of_2(uint32_t x) {
	return !(x & (x-1));
}
 
static inline uint32_t
next_pow_of_2(uint32_t x) {
	if ( is_pow_of_2(x) )
		return x;
	x |= x>>1;
	x |= x>>2;
	x |= x>>4;
	x |= x>>8;
	x |= x>>16;
	return x+1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值