What is the equivalent of python's chr() and ord() functions in golang?
chr(97) = 'a'
ord('a') = 97
Python ord() and chr() are built-in functions. They are used to convert a character to an int and vice versa. Python ord() and chr() functions are exactly opposite of each other.
Python ord() example For example, ord('a') returns the integer 97, ord('€') (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character's code point must be in the range [0..
The ord() function returns the number representing the unicode code of a specified character.
Python chr() and ord() Python's built-in function chr() is used for converting an Integer to a Character, while the function ord() is used to do the reverse, i.e, convert a Character to an Integer.
They are supported as simple conversions:
ch := rune(97)
n := int('a')
fmt.Printf("char: %c\n", ch)
fmt.Printf("code: %d\n", n)
Output (try it on the Go Playground):
char: a
code: 97
Note: you can also convert an integer numeric value to a string
which basically interprets the integer value as the UTF-8 encoded value:
s := string(97)
fmt.Printf("text: %s\n", s) // Output: text: a
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to
"\uFFFD"
.
It appears that a simple uint8('a')
will produce a correct output. To convert from integer to string string(98)
will suffice:
uint8('g') // 103
string(112) // p
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With