Recent

Author Topic: [SOLVED] Fnv-1a hash algorithm crashes with range check error  (Read 1792 times)

Hoch

  • New Member
  • *
  • Posts: 35
[SOLVED] Fnv-1a hash algorithm crashes with range check error
« on: August 05, 2023, 11:27:22 pm »
Hi,

I'm trying to execute a simple fnv-1a hash algorithm but it crashes with a range check error (Runerror(201)).

See attached screen capture.

This is the algorithm:

Code: Pascal  [Select][+][-]
  1. function fnv1a32 (constref str_to_hash: string): longword;
  2. var
  3.   str_pos: longword;
  4. begin
  5.   result := 2166136261;
  6.   for str_pos := 1 to length (str_to_hash) do
  7.     result := (result xor byte(str_to_hash[str_pos])) * 16777619;
  8. end;

The code crashes in this line:

Code: [Select]
result := (result xor byte(str_to_hash[str_pos])) * 16777619;

The problem is that the product of the multiplication is langer than a longword (32 bit).

I'm pretty sure that the translation from c to pascal is correct.

What I'm I doing wrong?...

Thanks in advance!  :)

 
« Last Edit: August 08, 2023, 08:40:18 am by Hoch »

Red_prig

  • Full Member
  • ***
  • Posts: 153
Re: Fnv-1a hash algorithm crashes with range check error
« Reply #1 on: August 05, 2023, 11:54:44 pm »
It looks like the algorithm assumes arithmetic overflow, so turn off range check in the project settings

Thaddy

  • Hero Member
  • *****
  • Posts: 19182
  • Glad to be alive.
Re: Fnv-1a hash algorithm crashes with range check error
« Reply #2 on: August 06, 2023, 12:08:22 pm »
If the compiler detects the value can in theory be larger than 32 bit it is expanded to 64 bit.
You can try this:
Code: Pascal  [Select][+][-]
  1. result := longword (result xor byte(str_to_hash[str_pos])) * 16777619);
IOW a longword cast before assigning the result.
You should have seen a hint or warning about the expansion to 64 bit.
« Last Edit: August 06, 2023, 12:17:34 pm by Thaddy »
objects are fine constructs. You can even initialize them with constructors.

Hoch

  • New Member
  • *
  • Posts: 35
Re: Fnv-1a hash algorithm crashes with range check error
« Reply #3 on: August 08, 2023, 08:34:32 am »
Thanks red_prig for the fast answer. That did the trick.

The runtime error also happens with other hash algorithms like murmurhash3 or xxhash.

Adding {$RANGECHECKS OFF} or {$OVERFLOWCHECKS OFF} solved the errors.

Thaddy solution also works fine and eliminates the runtime errors so you don't need to use the directives but I guess that it adds a little bit of logic to the loop...?

I also found that you can and the result bits with $FFFFFFFF to avoid the runtime errors. But you are adding an extra operation.

Thanks for the useful answers!  :)

 

TinyPortal © 2005-2018