Aleksei Chepovoi
Aleksei Chepovoi

Reputation: 3955

How to cast int digit to char without loosing digit value in c#

Mabby it's a stupid question, but how can I cast digit of type int to digit of type char?

Standard conversion OPs doesn't do this:

int x = 5;
char myChar = Convert.ToChar(5); // myChar is now a unicode character
char secondChar = (char)x; // again I get a unicode character, not a digit '5'

I need this because I have a method that returns IEnumerable of Char and I need to return a collection of ints somehow.

For instance:

int[] {1, 2, 3}  

convert to

char[] {'1', '2', '3'}  

Is it possible to do such a conversion in C#?

Upvotes: 2

Views: 6504

Answers (4)

Abhishek Deo
Abhishek Deo

Reputation: 149

This should work : (char) (i + '0')

Example: var i = 8; var c = (char) (i + '0');//Gives '8'

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

If you know for sure that the values are in the 0 .. 9 range (both inclusive), you can slightly improve efficiency by making use of a bitwise or, instead of addition:

(char) ('0' | i);

this works since '0' has as binary codepoint 0011 0000, and the ten digits thus all are between 0011 0000 and 0011 1001.

You can thus convert an IEnumerable<int> to an IEnumerable<char> with:

data.Select(i => (char) ('0' | i));

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

Add 48 to your int value before converting to char:

char c = (char)(i + 48);

Or for int[] -> char[] conversion:

var source = new int[] { 1, 2, 3 };
var results = source.Select(i => (char)(i + 48)).ToArray();

It works, because '0' character in ASCII table has 48 value. But it will work only if your int values is between 0 and 9.

Upvotes: 12

King King
King King

Reputation: 63317

var yourInts = new int[]{1,2,3};
var result = yourInts.Select(x=>x.ToString()[0]).ToArray();

Upvotes: 0

Related Questions