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

…衆ロ難τιáo~ 提交于 2019-12-11 03:29:24

问题


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.


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



回答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'));



回答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.




回答4:


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




回答5:


Use Convert.ToString() to perform this.



来源:https://stackoverflow.com/questions/10649440/how-to-convert-a-byte-to-a-char-e-g-1-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!