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
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Nim2
* Scala


[ edit | logout ]
[ sandbox | passwd ]

The ord() function

The ord() function (from std/system, link) is similar to Python.

The signature of the function:

func ord[T: Ordinal | enum](x: T): int {.magic: "Ord", ....}

The input parameter x is not necessarily a char! It can be an enum or an ordinal type. A char is also ordinal.

With ASCII

There's no problem with ASCII characters:

echo ord('A')         # 65

echo 'a'.ord          # 97

With Unicode

ord() with Unicode characters
print(ord("→"))    # 8594
import std/unicode

#echo ord('→')    # ERROR
# a char must be 1 byte long          

#echo ord("→")    # ERROR
# ord() cannot be called with a string          

echo ord("→".runeAt(0))   # 8594

I want to write about Unicode and UTF-8 encoding later.

Is short: a Rune in Nim is an int32. Any Unicode character can fit in an int32. The function .runeAt(0) takes the first Unicode character of the string. Since this arrow (→) cannot be stored in a char (since it's larger than 1 byte), the trick is to store it in a string and then extract the first Unicode character from it (though this string contains only 1 Unicode character). Again: more on this later.

What about Python? In Python, when you declare a char:

c = 'x'

then it's actually a 1-long string :) You can verify its type. Python does the heavy-lifting when you work with Unicode texts.

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 April 08, 12:17