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

17,721

Solution 1

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();

Solution 2

Simply using variable.ToString() should be enough. If you want to get fancy, add the ASCII code of 0 to the variable before converting:

Convert.ToChar(variable + Convert.ToByte('0'));

Solution 3

Use this for conversion.

(char)(mybyte + 48); 

where mybyte = 0 or 1 and so

OR

Convert.ToChar(1 + 48); // specific case for 1

While others have given solution i'll tell you why your (char)1 and Convert.ToChar(1) is not working.

When your convert byte 1 to char it takes that 1 as an ASCII value.

Now ASCII of 1 != 1.

Add 48 in it because ASCII of 1 == 1 + 48`. Similar cases for 0, 2 and so on.

Solution 4

Assume you have variable byte x; Just use (char)(x + '0')

Solution 5

Use Convert.ToString() to perform this.

Share:
17,721
brgerner
Author by

brgerner

C#, ReSharper, (Java)

Updated on June 05, 2022

Comments

  • brgerner
    brgerner almost 2 years

    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.