[fpc-pascal] Pointer hashing

Karoly Balogh (Charlie/SGR) charlie at scenergy.dfmk.hu
Mon Jan 30 07:02:10 CET 2017


Hi,

On Mon, 30 Jan 2017, Ryan Joseph wrote:

> I?m trying to hash a pointer value and found some example of hash
> function but not sure about translations and the process in general.
>
> 1) Should I cast ?pointer? as PtrUInt to get an integer from a pointer?
> I?m looking for the memory address I guess and casting seems to return a
> unique value. Btw, these functions are for a 32 bit integer but I?m
> building for 64 bit. How do I deal with that? Can I remove the upper
> 32bits which are typically not used.

This hash function doesn't deal with the upper 32bit, therefore it's
probably unsuitable to properly hash 64bit pointers. You need to find an
alternative hash function which does that, if you need 64bit. (Googling
reveals some relevant pages for a 64bit version, if you search that magic
hex number in there...)

> 2) I?m getting incompatible type errors on my translation. What did I do
> wrong there? The fact the function is 32 bit may be the problem?
>
> unsigned int hash(unsigned int x) {
>     x = ((x >> 16) ^ x) * 0x45d9f3b;
>     x = ((x >> 16) ^ x) * 0x45d9f3b;
>     x = (x >> 16) ^ x;
>     return x;
> }
>
> function Hash (x: PtrUInt): PtrUInt;
> begin
>   x := (Power((x shr 16), x)) * $45d9f3b;
>   x := (Power((x shr 16), x)) * $45d9f3b;
>   x := Power((x shr 16), x);
>   result := x;
> end;
>
> Thanks for any ideas you have.

The "^" operator in C simply doesn't translate to "Power" in Pascal. It's
"exclusive or", a.k.a. xor. So that line in C translates to:

x:=((x shr 16) xor x) * $45d9f3b;

Furthermore the Power() function in Math unit seems to deal with Floats
and returns Float, where your type errors might come. But since you don't
need Power() there anyway, that should be an easy fix...

Charlie



More information about the fpc-pascal mailing list