我正在尝试对哈希表程序的给定键执行一些按位操作。我想弄清楚的方法是折叠,中间正方形,截断和基数。我不希望任何人给我直接的答案,但帮助发送给我正确的方向。我找不到任何涉及此的通信或帮助,或任何可能有帮助的算法。我有一个按位程序,它显示了二进制数的一些操作,例如shift,XOR,OR,AND<等等。我不理解的是如何只选择32位二进制数的一部分,例如在中间正方形中,您将选择中间的四位,并仅使用操作中的那些。我尝试了几件事,但以下是我最终的结果。我认为中间广场的作品(虽然不确定),但似乎只适用于大整数。折叠和截断肯定不起作用。我甚至没有尝试过基数法。任何帮助,指导或向我推荐最有用的文档都会很棒。
int location = 0;
if(hFunction == FOLDING){
location = (key & 0xff000000) >> 2;
location = location + ((key & 0x00ff0000) >> 2);
location = location + ((key & 0x0000ff00) >> 2);
location = location + ((key & 0x000000ff) >> 2);
cout << "\n" << location << "\n"; // for debuggin
}
else if(hFunction == MIDSQUARE){
location = ((key * key) & 0x00ffff00) >> 2;
cout << "\n" << location << "\n"; // for debuggin
}
else if(hFunction == TRUNCATION){
location = (key & 0x000ffff0) << 1;
cout << "\n" << location << "\n"; // for debugging
}
else if(hFunction == RADIX){
return(0);
}
// Divsion Method
location %= tableSize;
keys++;
return(location);
编辑(修订): 好的,这是我做的一些修改。我不知道这些是否正确,但让我知道什么可以改变,更好地优化,并且是完全错误的。我得到了所有四种方法的输出,但不管是否可以,我还不知道。我没有彻底检查每一个。
修订后的代码:
int location = 0;
// splits key and adds the sections together - discards remainder
if(hFunction == FOLDING){
while (key != 0){
location = location + key % 100;
key = key / 100;
}
//cout << location << "\n"; // for debugging
}
// squares the key and then shifts right 2 spaces
else if(hFunction == MIDSQUARE){
location = ((key * key) & 0x00ffff00) << 2;
//cout << location << "\n"; // for debugging
}
// mods the key by 100, then divides by 10, splitting it into different digits,
// then adds those digits together
else if(hFunction == TRUNCATION){
while (key != 0){
location = location + key % 100;
key = key / 10;
}
//cout << location << "\n"; // for debugging
}
// converts the key to a character array while also taking all digits of the key and
// multiplying them by base 5, then converts back to an integer
else if(hFunction == RADIX){
char buffer[33];
_itoa_s(key, buffer, 5);
//cout << key; // for debugging
//system("pause"); // for debugging
location = atoi(buffer);
//cout << location << "\n"; // for debugging
}
// Divsion Method
location %= tableSize;
keys++; // counts the keys per hash table
return(location);