Last active
January 9, 2024 08:49
-
-
Save wjkoh/39d9a108f3e73bc728172492670bb97a to your computer and use it in GitHub Desktop.
Dart/Flutter: FNV-1a 64-bit hash function (Web compatible)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples: