好的,所以我只是想出了一种如何将8位二进制代码转换为数字的方法(或者我认为),然后通过编写适合您的程序,有什么更好的学习方法!而且我有点被卡住了。我试图找出如何将字符串转换为字符串array [],这样我就可以遍历它并将所有内容加在一起,但是我似乎找不到不需要空格或任何内容的东西。任何人有任何想法吗?这是我的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace binary_to_number
{
class Program
{
static int GetAddition(int place)
{
switch(place) // goes through the switch until if finds witch place the binary is in
{
case 1:
return 128;
case 2:
return 64;
case 3: return 32;
case 4: return 16;
case 5: return 8;
case 6: return 4;
case 7: return 2;
case 8: return 1;
default: return 0;
}
}
static int ToInt(string input)
{
string[] binary = input.Split(); // right here is where im stuck
int thenumber = 0; // this is the number it adds to
for(int i = 0;i < 9;i++)
{
Console.WriteLine(binary[i]);
}
return thenumber;
}
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Please put in a 8-digit binary");
string input = Console.ReadLine();
if (input.Length < 9) // binary has 8 digits plus the null at the end of each string so if its
{ // not binary
Console.WriteLine(ToInt(input)); // function converts the input into binary
}
}
}
}
}
答案 0 :(得分:0)
希望这会对您有所帮助。 String实现IEnumerable接口,该接口将为您提供用于枚举的枚举器。
Console.WriteLine("Please enter 8 digit binary number");
string input = Console.ReadLine();
foreach (var item in input)
{
Console.WriteLine("Item is {0}", item);
}
答案 1 :(得分:0)
要开始修复程序,请执行以下操作:
string[] binary = input.Split(); // right here is where im stuck
应该是
char[] binary = input.ToCharArray();
另外for (int i = 0; i < 9; i++)
应该是for (int i = 0; i < 8; i++)
或更好的for (int i = 0; i < binary.Length; i++)
通过使用Convert
类,您可以节省大量代码。
while (true)
{
Console.WriteLine("Please put a value as binary");
string input = Console.ReadLine();
var number = Convert.ToUInt16(input, 2);
Console.WriteLine($"input:{input}, value: {number}, as binary: {Convert.ToString(number, 2)}");
}
/*
Please put a value as binary
1
input:1, value: 1, as binary: 1
Please put a value as binary
11
input:11, value: 3, as binary: 11
Please put a value as binary
10000001
input:10000001, value: 129, as binary: 10000001
*/