如何投放INT位没有在C#中失去位数值为char [英] How to cast int digit to char without loosing digit value in c#

查看:134
本文介绍了如何投放INT位没有在C#中失去位数值为char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mabby这是一个愚蠢的问题,但我怎么能投int类型的数字为char类型的数字吗?

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

标准转换的OP没有做到这一点:

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'



我需要这个,因为我有返回的方法的IEnumerable 字符,我需要返回 int类型的集合不知何故。

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

例如:

int[] {1, 2, 3}  

转换成

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

是否有可能在C#中做这样的转换?

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

推荐答案

添加 48 你的 INT 值转换为字符之前:

Add 48 to your int value before converting to char:

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

或者为 INT [] - > 的char [] 转换:

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

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



它的工作原理,因为 0 字符在 ASCII表 48 值。但它只会工作,如果你的 INT 的值是 0 9

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.

这篇关于如何投放INT位没有在C#中失去位数值为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆