the magic of MAGIC numbers
Have you ever seen them?
The cute little #defines and consts that have weird looking values like 0x81772012 or 0x49122035, used allover the code...
the purpose which is known to only to their author ???
If you ever had interest in encrypting you're probably acquainted with them
(Berkely DB has a full load of them! )
i was wondering how people invent them!
is it like "hmm let see ... square of 0x1231 minus 0x121909 plus 0x93abde XOR 0x132958 add one more AND VOILA !! thats the number that solves my problems!!! "
and also if you have some interesting and working code loaded with them share it !
heres some :
Code:
//Berkely DB hashing algorithms (one of the best i've ever seen)
#define DCHARHASH(h, c) ((h) = 0x63c63cd9*(h) + 0x9c39c33d + (c))
#define UINT8 unsigned char
UINT Hashfunc1(const void *key,UINT len)
{
const UINT8 *e, *k;
UINT h;
UINT8 c;
k = key;
e = k + len;
for (h = 0; k != e;) {
c = *k++;
if (!c && k > e)
break;
DCHARHASH(h, c);
}
return h;
}
//////Better
unsigned int Hashfunc2(const void *key,UINT len)
{
const unsgined char *e, *k;
unsigned int h;
k = key;
e = k + len;
for (h = 0; k < e; ++k) {
h *= 16777619; //what is that MAGIC ?!?!?!
h ^= *k;
}
return h;
}
Code:
//author :Praveena <[email protected]>
//descr: some encrypting scheme i found
//the folowing code is used for generating
// key seeds
#define cypher 8
#define CYPHER_SZ (8*sizeof(int32_t))
typedef char int8_t;
typedef short int16_t;
typedef int int32_t;
typedef __int64 int64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned __int64 uint64_t;
void modseed(int32_t seed[cypher]) {
int x;
for(x=1;x<cypher;x++)
seed[x]=seed[x]*0x81772012+seed[x]+0x49122035+seed[x+1];
for(x=1;x<cypher;x++)
seed[0] ^= seed[x];
}
int seedsum(int32_t seed[cypher]) {
int n,x;
n=0x80379251;
for(x=0;x<cypher;x++)
n=n^seed[x];
return ((n>>24)^((n>>16)&255)^((n>>8)&255)^(n&255));
}
void seed_gen(char *pwd,int32_t seed[cypher]) {
char *pp = pwd;
memset((void*)seed,0,CYPHER_SZ);
modseed(seed);
while((*pp)){
modseed(seed);
seed[0]=seed[0]+(*pp);
modseed(seed);
pp++;
}
}
// and encoding
int encode(char *buf,char *password) {
int ret = 0;
char *pstr = buf;
int seed[cypher];
seed_gen(password,seed);
while(*pstr) {
modseed(seed);
*pstr ^= (char)(seedsum(seed));
pstr++;
}
*pstr = '\0';
return 1;
}