将字符串转换为整数数组C#
我是一名C#新手,正在学习如何使用数组。我编写了一个小型控制台应用程序,可以将二进制数转换为十进制数;然而,我使用的sytax似乎在某种程度上导致应用程序使用整数的unicode名称,而不是整数本身的真值,因此1变为49,0变为48 我如何以不同的方式编写应用程序来避免这种情况?谢谢将字符串转换为整数数组C#,c#,arrays,string,C#,Arrays,String,我是一名C#新手,正在学习如何使用数组。我编写了一个小型控制台应用程序,可以将二进制数转换为十进制数;然而,我使用的sytax似乎在某种程度上导致应用程序使用整数的unicode名称,而不是整数本身的真值,因此1变为49,0变为48 我如何以不同的方式编写应用程序来避免这种情况?谢谢 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threadin
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Key in binary number and press Enter to calculate decimal equivalent");
string inputString = Console.ReadLine();
////This is supposed to change the user input into character array - possible issue here
char[] digitalState = inputString.ToArray();
int exponent = 0;
int numberBase = 2;
int digitIndex = inputString.Length - 1;
int decimalValue = 0;
int intermediateValue = 0;
//Calculates the decimal value of each binary digit by raising two to the power of the position of the digit. The result is then multiplied by the binary digit (i.e. 1 or 0, the "digitalState") to determine whether the result should be accumulated into the final result for the binary number as a whole ("decimalValue").
while (digitIndex > 0 || digitIndex == 0)
{
intermediateValue = (int)Math.Pow(numberBase, exponent) * digitalState[digitIndex]; //The calculation here gives the wrong result, possibly because of the unicode designation vs. true value issue
decimalValue = decimalValue + intermediateValue;
digitIndex--;
exponent++;
}
Console.WriteLine("The decimal equivalent of {0} is {1}", inputString, intermediateValue);
Console.ReadLine();
}
}
}
只需使用以下代码
for (int i = 0; i < digitalState.Length; i++)
{
digitalState[i] = (char)(digitalState[i] - 48);
}
请注意,字符的值(例如“1”)与它所表示的值不同。正如您已经注意到的,“1”等于ASCII码49。当你从它的值(49)中减去48,它变为1 @CharlesMager说了一切。然而,我认为这是一个家庭作业。正如你所说,乘以ASCII值是错误的。所以只需从ASCII值中减去“0”(十进制值48)
intermediateValue = (int)Math.Pow(numberBase, exponent)
* ((int)digitalState[digitIndex] - 48);
你的代码很难看,没有必要从字符串开始倒转。另外,使用
Math.Power
效率低下,移位(有两个错误:您错过了“-48”并写入了中间值而不是结果(最后一行)。不确定如何取消代码块中的某些部分的线;)
我知道这并不能真正回答您的问题,但您的所有代码都可以简化为Convert.ToInt32(inputString,2)
-请参阅。不用担心。我正试图找出数组和循环结构的语法;因此,代码就显得非常笨拙。不过,您的方法仍然值得了解-谢谢。讽刺的是,这个问题正确地引用了Unicode,而一些答案错误地引用了ASCII。
intermediateValue = (int)Math.Pow(numberBase, exponent)
* ((int)digitalState[digitIndex] - 48);
long v = 0;
foreach (var c in inputString)
{
v = (v << 1) + ((int)c - 48);
}
Console.WriteLine("The decimal equivalent of {0} is {1}", inputString, v);
Console.ReadLine();
intermediateValue = (int)Math.Pow(numberBase, exponent) * (digitalState[digitIndex]-48;
//The calculation here gives the wrong result,
//possibly because of the unicode designation vs. true value issue
decimalValue += intermediateValue;
(.....)
Console.WriteLine("The decimal equivalent of {0} is {1}", inputString, decimalValue);