我有一些C#的基本知识,但我在编写一些看似简单的概念时遇到了麻烦。我想读取包含
等值的文件(.asm)@1
@12
@96
@2
@46
etc.
多个连续行上的。然后我想摆脱@符号(如果它们存在),将剩余的数值转换为二进制,然后将这些二进制值写回自己的行上的新文件(.hack)。线路数量没有限制,这是我最大的问题,因为我不知道如何动态检查线路。到目前为止,我只能读取和转换行,如果我编写代码来查找它们,那么我就无法弄清楚如何在新文件中将这些值写在自己的行上。对不起,如果这听起来有点令人费解,但任何帮助将不胜感激。谢谢!
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var line = File.ReadAllText(openFileDialog1.FileName);
using (StreamWriter sw = File.CreateText("testCode.hack"))
{
var str = line;
var charsToRemove = new string[] {"@"};
foreach (var c in charsToRemove)
{
str = str.Replace(c, string.Empty);
}
int value = Convert.ToInt32(str);
string value2 = Convert.ToString(value, 2);
if (value2.Length < 16)
{
int zeroes = 16 - value2.Length;
if(zeroes == 12)
{
sw.WriteLine("000000000000" + value2);
}
}
else
{
sw.WriteLine(value2);
}
}
答案 0 :(得分:0)
我的建议是创建一个List<string>
。这是步骤
StreamWriter
输出(.hack)文件。 List<string>
修改字符串并写入文件。代码示例:
List<string> lstInput = new List<string>();
using (StreamReader reader = new StreamReader(@"input.asm"))
{
string sLine = string.Empty;
//read one line at a time
while ((sLine = reader.ReadLine()) != null)
{
lstInput.Add(sLine);
}
}
using (StreamWriter writer = new StreamWriter(@"output.hack"))
{
foreach(string sFullLine in lstInput)
{
string sNumber = sFullLine;
//remove leading @ sign
if(sFullLine.StartsWith("@"))
sNumber = sFullLine.Substring(1);
int iNumber;
if(int.TryParse(sNumber, out iNumber))
{
writer.WriteLine(IntToBinaryString(iNumber));
}
}
}
public string IntToBinaryString(int number)
{
const int mask = 1;
var binary = string.Empty;
while(number > 0)
{
// Logical AND the number and prepend it to the result string
binary = (number & 1) + binary;
number = number >> 1;
}
return binary;
}
参考:IntToBinaryString方法。
注意:@TheDutchMan答案中提到的Int to Binary String方法是更好的选择。
答案 1 :(得分:0)
此代码可以帮助您快速实现目标:
static void Main(string[] args)
{
string line = string.Empty;
System.IO.StreamReader reader = new System.IO.StreamReader(@"C:\test.txt");
System.IO.StreamWriter writer = new System.IO.StreamWriter(@"C:\test.hack");
while ((line = reader.ReadLine()) != null) // Read until there is nothing more to read
{
if (line.StartsWith("@"))
{
line = line.Remove(0, 1); // Remove '@'
}
int value = -1;
if (Int32.TryParse(line, out value)) // Check if the rest string is an integer
{
// Convert the rest string to its binary representation and write it to the file
writer.WriteLine(intToBinary(value));
}
else
{
// Couldn't convert the string to an integer..
}
}
reader.Close();
writer.Close();
Console.WriteLine("Done!");
Console.Read();
}
//http://www.dotnetperls.com/binary-representation
static string intToBinary(int n)
{
char[] b = new char[32];
int pos = 31;
int i = 0;
while (i < 32)
{
if ((n & (1 << i)) != 0)
{
b[pos] = '1';
}
else
{
b[pos] = '0';
}
pos--;
i++;
}
return new string(b);
}