我有一个.txt文件,其中包含Pi的5亿位二进制表示.
我需要在我的程序中使用它的字符串表示.我还需要能够搜索子串等等 - 换句话说,我需要能够像正常大小的字符串一样对待它.我会试着找到很多子串,所以速度是必要的.
我最初的逻辑是简单地将字符串直接复制并粘贴到程序中并将其用作静态变量..但我无法实际打开.txt文件,因此无法复制和粘贴.我的下一次尝试是从文件中读取整个字符串,但我不能在静态方法中执行此操作,并且WAAAY需要太长时间(实际上我不确切知道需要多长时间,我最终关闭了程序).
是否有可能做到这一点?任何帮助,将不胜感激.
编辑:潜在的相关信息:
使用此代码:
/// <summary>
/// Gets a 500 million binary digit representation of Pi.
/// </summary>
public static string GetPi()
{
//as per http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx
StreamReader piStream = new StreamReader(@"C:\binaryPi.txt");
string pi = "";
string line;
while ((line = piStream.ReadLine()) != null)
{
pi += line;
}
return pi;
}
Run Code Online (Sandbox Code Playgroud)
我得到一个OutOfMemoryException ..所以扫描文件实际上似乎不可能,除非我遗漏了什么..
我建议你创建一个可以处理这种数据的自定义类.
如果文件的内容是pi的二进制形式的表示,那么它只是零和一.如果将每个位存储在实际位中,则每个二进制数字使用1/8字节,而如果将其存储为文本,则每个位将使用两个字节.通过以更紧凑的形式存储,您将使用1/16的内存.
然后,您的课程必须处理您在数据中搜索位模式的方式.这将是棘手的部分,但如果您创建八个不同版本的搜索模式,转移到匹配一个字节中的八个可能位置,搜索可能比搜索字符串更有效.
这是一个开始......
public class BitList {
private byte[] _data;
private int _count;
public BitList(string fileName) {
using (FileStream s = File.OpenRead(fileName)) {
_data = new byte[(s.Length + 7) / 8];
_count = 0;
int len;
byte[] buffer = new byte[4096];
while ((len = s.Read(buffer, 0, buffer.Length)) > 0) {
for (int i = 0; i < len; i++) {
switch (buffer[i]) {
case 48: Add(0); break;
case 49: Add(1); break;
}
}
}
}
}
public void Add(int bit) {
_data[_count / 8] |= (byte)(bit << (_count % 8));
_count++;
}
public int this[int index] {
get {
return (_data[index / 8] >> (index % 8)) & 1;
}
}
}
Run Code Online (Sandbox Code Playgroud)
(注意:此代码未经过测试,但您至少应该获得原则.)
| 归档时间: |
|
| 查看次数: |
2325 次 |
| 最近记录: |