0

I'm using Arabic CultureInfo in a C# project. At one place I'm converting the character code to character using Strings.Chr(chrCode) if the language which I select is English it is working fine, other than English it is returning some special characters.

If I choose Arabic CultureInfo it is returning Arabic characters instead of English characters.

Please suggest me how to get English characters when I choose other CultureInfo.

  • The Chr() function is legacy, used 20+ years ago when the OS was not yet Unicode at its core, programs still used 8-bit characters and code pages were still common. Today you must use ChrW() and AscW(). – Hans Passant Nov 21 '17 at 09:33

1 Answers1

1

Are you looking for Win-1256 code page (Strings.Chr doesn't work with Unicode, but with code pages)?

// From arabic letter Ḍād to its one byte code (Win-1256)
byte code = Encoding.GetEncoding(1256).GetBytes("\u0636")[0];
// From code back to arabic letter 
char back = Encoding.GetEncoding(1256).GetString(new byte[] { code })[0];

Console.WriteLine($"{back} == {code} (\\u{(int)back:x4})");

If you want to wrap it into a method:

private static char ArabicChr(int chrCode) {
  if (chrCode < byte.MinValue || chrCode > byte.MaxValue)
    throw new ArgumentOutOfRangeException(
      "chrCode",
     $"chrCode must be in [{byte.MinValue}..{byte.MaxValue}] range");

  return Encoding.GetEncoding(1256).GetString(new byte[] { (byte)chrCode })[0];
}

Outcome:

ض == 214 (\u0636)

Edit: If you want to obtain English characters, you can try using Win-1252 code page:

private static char EnglishChr(int chrCode) {
  if (chrCode < byte.MinValue || chrCode > byte.MaxValue)
    throw new ArgumentOutOfRangeException(
      "chrCode",
     $"chrCode must be in [{byte.MinValue}..{byte.MaxValue}] range");

  return Encoding.GetEncoding(1252).GetString(new byte[] { (byte)chrCode })[0];
}

In general case, if you have culture's name, e.g. "en-US":

private static char Chr(int chrCode, string cultureName = "en-US") {
  if (chrCode < byte.MinValue || chrCode > byte.MaxValue)
    throw new ArgumentOutOfRangeException(
      "chrCode",
     $"chrCode must be in [{byte.MinValue}..{byte.MaxValue}] range");

  int page = CultureInfo.GetCultureInfo(cultureName).TextInfo.ANSICodePage;

  return Encoding.GetEncoding(page).GetString(new byte[] { (byte)chrCode })[0];
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • @Abhishek Hotte: if you want *English* characters when workring with Arabic culture, you should use `1252` code page (see my edit) – Dmitry Bychenko Nov 21 '17 at 13:57