Python CityHash64 Code Example (Online Runner)
Python CityHash64 examples with decimal output and file hashing to match the CityHash tools.
Online calculator: use the site CityHash text tool.
Note: This snippet requires locally installed dependencies and will not run in the online runner.
Calculation method
CityHash64 returns a 64-bit integer. The online tool displays the unsigned decimal value, so the helper below masks it to 64 bits and returns a base-10 string.
Python requires the cityhash package: pip install cityhash.
Implementation notes
- Package:
cityhashis a wrapper around Google CityHash. - Implementation: the helper uses
CityHash64and masks to 64 bits so the output matches the unsigned decimal UI value. - Notes: CityHash is not cryptographic and is intended for hash tables or checksums, not security.
python
from pathlib import Path
import cityhash
UINT64_MASK = (1 << 64) - 1
def cityhash64_text(text: str, encoding: str = "utf-8") -> str:
value = cityhash.CityHash64(text.encode(encoding)) & UINT64_MASK
return str(value)
def cityhash64_file(path: Path) -> str:
value = cityhash.CityHash64(path.read_bytes()) & UINT64_MASK
return str(value)
# Example usage
print(cityhash64_text("hello"))
File hashing example
python
from pathlib import Path
import tempfile
import cityhash
UINT64_MASK = (1 << 64) - 1
def cityhash64_file(path: Path) -> str:
value = cityhash.CityHash64(path.read_bytes()) & UINT64_MASK
return str(value)
with tempfile.TemporaryDirectory() as temp_dir:
sample_path = Path(temp_dir) / "sample.bin"
sample_path.write_bytes(b"hello")
print(cityhash64_file(sample_path))Complete script (implementation + tests)
python
import cityhash
UINT64_MASK = (1 << 64) - 1
def cityhash64_text(text: str) -> str:
return str(cityhash.CityHash64(text.encode("utf-8")) & UINT64_MASK)
def run_tests() -> None:
raw_empty = cityhash.CityHash64(b"") & UINT64_MASK
raw_hello = cityhash.CityHash64(b"hello") & UINT64_MASK
assert cityhash64_text("") == str(raw_empty)
assert cityhash64_text("hello") == str(raw_hello)
print("CityHash tests passed")
if __name__ == "__main__":
run_tests()