一个求平方根倒数的函数(精度不高)
/* 来自 Quake 3 的源码 */
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = *(int*)&x;
i = 0x5f3759df - (i >> 1);
x = *(float*)&i;
x = x * (1.5f - xhalf * x * x);
return x;
}
一个求平方根的函数(精度不高)
/* 来自 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));
}
字符串 hash 函数之一
一个方便的 hash 函数应该散列的比较开,计算速度跟字符串长度关系不大,又不能只计算字符串的开头或末尾。这里的算法是从 Lua 中看来的。
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 函数之二
unsigned long hashInfoTable[0x500];
void prepareHashInfoTable()
{
unsigned long seed = 0x00100001, index1 = 0, index2 = 0, i;
for( index1 = 0; index1 < 0x100; index1++ )
{
for( index2 = index1, i = 0; i < 5; i++, index2 += 0x100 )
{
unsigned long temp1, temp2;
seed = (seed * 125 + 3) % 0x2AAAAB;
temp1 = (seed & 0xFFFF) << 0x10;
seed = (seed * 125 + 3) % 0x2AAAAB;
temp2 = (seed & 0xFFFF);
hashInfoTable[index2] = ( temp1 | temp2 );
}
}
}
unsigned long HashString(const char* lpszFileName, unsigned long dwHashType)
{
const char *key = lpszFileName;
unsigned long seed1 = 0x7FED7FED, seed2 = 0xEEEEEEEE;
int ch;
while(*key != 0)
{
ch = toupper(*key++);
seed1 = hashInfoTable[(dwHashType << 8) + ch] ^ (seed1 + seed2);
seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3;
}
return seed1;
}
快速 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));
assert ((*t & 0xc0) != 0x80);
for (int i = 1; i < 3; i++) {
if ((t & 0xc0) != 0x80) {
break;
}
ret = (ret << 6) | (t & 0x3f);
}
return ret;
}
取一个介于0~255之间随机整数的函数
static byte RndFactorA = 12;
static byte RndFactorB = 45;
int randInt()
{
RndFactorA += (RndFactorB & 0xFF);
RndFactorA += (RndFactorB & 0xFF) >>2 ;
RndFactorB ^= (RndFactorA & 0xFF);
RndFactorB += (RndFactorA & 0xFF) >>1 ;
return RndFactorA & 0xFF;
}