Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to format integer as ASCII/Unicode character (WITHOUT just casting to char)
    text
    copied!<p>Is there a way to format an integer as the equivalent ASCII/Unicode character in C#? For example, if I have the following code:</p> <pre><code>int n = 65; string format = ""; // what? string s = string.Format(format, n); </code></pre> <p>what do I need to put in the string <code>format</code> to result a single character, 'A', being written to <code>s</code> - basically I'm looking for the equivalent of doing the following in C:</p> <pre><code>int n = 65; char s[2]; char format = "%c"; sprintf(s, format, n); /* s &lt;- 'A' */ </code></pre> <p><strong>EDIT</strong> </p> <p>I should probably explain a bit more about what I'm trying to do, as the obvious answer "cast it to char", doesn't help.</p> <p>I have a situation where I have an integer value that represents a bank account check digit, but which needs to be output as a character for some countries and a (0-padded) digit string for others. I'm wondering if there's a way of switching between the two just by changing the format string, so I can hold a dictionary of the appropriate format strings, keyed on the country code.</p> <p><strong>EDIT 2</strong></p> <p>(For Oded) something like this ...</p> <pre><code>IDictionary&lt;string, string&gt; ccFormat = new Dictionary&lt;string, string&gt;() { { "GB", "{0:D}" }, // 0-9 { "PT", "{0:D2}" }, // 00-99 { "US", "{0:D3}" }, // 000-999 { "IT", ???? } // A-Z -- What should ???? be? }; string FormatCheckDigits(int digits, string country) { return string.Format(ccFormat[country], digits); } </code></pre> <p>Currently I've got <code>????</code> as <code>null</code> and some special case code in the method:</p> <pre><code>string FormatCheckDigits(int digits, string country) { string format = ccFormat[country]; if (string.IsNullOrEmpty(format)) { // special case: format as A-Z return ((char) digits).ToString(); } else { // Use retrieved format string return string.Format(format, digits); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload