Search code examples
c#charbyte

How to convert a byte to a char, e.g. 1 -> '1'?


How to convert a byte to a char? I don't mean an ASCII representation. I have a variable of type byte and want it as a character.

I want just following conversions from byte to char:
0 ->'0'
1 ->'1'
2 ->'2'
3 ->'3'
4 ->'4'
5 ->'5'
6 ->'6'
7 ->'7'
8 ->'8'
9 ->'9'

(char)1 and Convert.ToChar(1) do not work. They result in '' because they think 1 is the ASCII code.


Solution

  • the number .ToString();

    one.ToString(); // one.ToString()[0] - first char -'1'
    two.ToString(); // two.ToString()[0] - first char -'2'
    

    Note that you can't really convert a byte to a char
    char is one char while byte can even three digits value!


    If you want to use LINQ and you're sure the byte won't exceed one digit(10+) you can use this:

    number.ToString().Single();