Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

Programming 1 (BI)
  ▸ exercises
  ▸ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ✦C++, ✦Clojure, ✦Scala


[ edit | logout ]
[ sandbox | passwd ]

generate a random hash

See also std/hashes .

Task: you want to generate a random hash. For instance, you want to store key/value pairs in a dictionary and you need a unique hash for the keys. Or, you want to create a temp file and you want to give it a unique name and for that you need a hash value.

In a previous post we saw the epochTime() function. We'll use that.

It's not a cryptographically secure method but for a simple task it should be enough.

import std/strutils    # strip, split, join
import std/strformat   # &"Hello {name}!"

import std/times
import std/hashes

let
  et = epochTime()
  h = hash(et).abs  # make it positive

echo hash(et)  # -4939203597474457342 ; can be negative

echo h  # 4939203597474457342

echo &"{h:x}"  # 448b9380bccbe6fe ; converted to hex

The hash() function is heavily overloaded, thus you can pass almost anything to it. It also accepts a string, so in the worst case just convert your thing to string with the `$` operator and pass it like that.

hash() returns an int that can be a negative value too.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 May 17, 15:14