Skip to main content
 首页 » 编程设计

c#之将数字对应的chars转换为uint

2024年02月13日11wuhuacong

我需要遍历字符串,应该是数字串,并对这些数字进行一些算术运算

for (int i = data.Length - 1; i >= 0; --i) 
  { 
       uint curDigit; 
       //Convert  to uint the current rightmost digit, if convert fails return false (the valid data should be numeric) 
       try 
       { 
           curDigit = Convert.ToUInt32(data[i]); 
           //arithmetic ops... 
       } 
       catch 
       { 
         return false; 
       } 

我使用以下输入数据字符串对其进行测试。 “4000080706200002” 对于 i = 15,对应于最右边的数字 2,我得到 50 作为

的输出
curDigit = Convert.ToUInt32(data[i]); 

谁能解释一下哪里出了问题,以及如何解决这个问题

请您参考如下方法:

50 是 '2' 的 ascii 码。你需要的是 '2' - '0' (50-48)

byte[] digits = "4000080706200002".Select(x => (byte)(x - '0')).ToArray(); 

http://www.asciitable.com/