Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Last active January 9, 2024 08:49
Show Gist options
  • Save wjkoh/39d9a108f3e73bc728172492670bb97a to your computer and use it in GitHub Desktop.
Save wjkoh/39d9a108f3e73bc728172492670bb97a to your computer and use it in GitHub Desktop.
Dart/Flutter: FNV-1a 64-bit hash function (Web compatible)
import 'dart:convert';
final fnv1A64Init = BigInt.parse("0xcbf29ce484222325");
final fnv1A64Prime = BigInt.from(0x100000001b3);
final uint64Mask = BigInt.parse("0xffffffffffffffff");
// FNV-1a 64-bit hash function (JavaScript compatible)
// This function is for you if you have seen errors like "Error: The integer literal 0xcbf29ce484222325 can't be represented exactly in JavaScript."
String fnv1A64(String string) {
var hash = fnv1A64Init;
final bytes = utf8.encode(string);
for (final b in bytes) {
hash ^= BigInt.from(b);
hash *= fnv1A64Prime;
}
hash &= uint64Mask;
return hash.toRadixString(16).padLeft(16, '0');
}
@wjkoh
Copy link
Author

wjkoh commented Jan 9, 2024

Examples:

fnv1A64('throne') == '265610cb61f74d53'
fnv1A64('crown') == '0c29519f09f0f250'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment