Is there a C# equivalent of Pythons chr and ord?
Asked Answered
C

2

8

I'm currently learning C# and was wondering if C# has an equivalent to chr and ord.

Chacma answered 28/2, 2019 at 14:52 Comment(3)
Just cast, if c is of type char and i is of type int: char c = (char) i; and int i = c;Eighth
learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/…Steiermark
Explicit cast it!Call
E
10

In C#, char is efficiently UInt16; that's why we can simply cast:

chr: (char) explicit cast (if i is out of [0..UInt16.MaxValue] range we'll have integer overflow)

 int i = ...
 char c = (char) i; 

ord: either (int) or even implicit cast (cast from char to int is always possible)

 char c = ...
 int i = c;
Eighth answered 28/2, 2019 at 14:56 Comment(0)
F
3

In Python 3, the strings work in terms of Unicode code points, whereas in C# the char is a UTF-16 code unit so if you cast between int and char you won't be able to handle characters outside the Basic Multilingual Plane.

If handling non-BMP code points matters to you, the equivalent of chr would be char.ConvertFromUtf32(int) - this returns a string as non-BMP characters will end up being represented as two UTF-16 code units.

The equivalent of ord would be char.ConvertToUtf32(string, int) which would allow you to find the code point at the given index in a string, taking account of whether or not it is made up of two UTF-16 code units. In contrast, if you have a char then the best you can do is a cast.

Fipple answered 28/2, 2019 at 21:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.