我有一个程序写保存一个文本文件使用stdio接口。它将4 MSB与4 LSB交换,但字符CR和/或LF除外。
我试图使用C#程序来“解码”这个流,但是我无法获得原始的字节。
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader("XXX.dat", Encoding.ASCII);
string sLine;
while ((sLine = sr.ReadLine()) != null) {
string s = "";
byte[] bytes = Encoding.ASCII.GetBytes(sLine);
for (int i = 0; i < sLine.Length; i++) {
byte c = bytes[i];
byte lb = (byte)((c & 0x0F) << 4), hb = (byte)((c & 0xF0) >> 4);
byte ascii = (byte)((lb) | (hb));
s += Encoding.ASCII.GetString(new byte[] { ascii });
}
sb.AppendLine(s);
}
sr.Close();
return (sb);我曾尝试更改UTF8中的编码,但它不起作用。我也使用了一个使用'sr‘StreamReader创建的BinaryReader,但是没有什么好的结果。
StringBuilder sb = new StringBuilder();
StreamReader sr = new StreamReader("XXX.shb", Encoding.ASCII);
BinaryReader br = new BinaryReader(sr.BaseStream);
string sLine;
string s = "";
while (sr.EndOfStream == false) {
byte[] buffer = br.ReadBytes(1);
byte c = buffer[0];
byte lb = (byte)((c & 0x0F) << 4), hb = (byte)((c & 0xF0) >> 4);
byte ascii = (byte)((lb) | (hb));
s += Encoding.ASCII.GetString(new byte[] { ascii });
}
sr.Close();
return (sb);如果文件以0xF2 0xF2 ...开头,我将读取除预期值之外的所有内容。错误在哪里?(即: 0xF6 0xF6)。
实际上,这段C代码完成了这项工作:
...
while (fgets(line, 2048, bfd) != NULL) {
int cLen = strlen(xxx), lLen = strlen(line), i;
// Decode line
for (i = 0; i < lLen-1; i++) {
unsigned char c = (unsigned char)line[i];
line[i] = ((c & 0xF0) >> 4) | ((c & 0x0F) << 4);
}
xxx = realloc(xxx , cLen + lLen + 2);
xxx = strcat(xxx , line);
xxx = strcat(xxx , "\n");
}
fclose(bfd);C#代码中有什么错误?
发布于 2010-03-04 14:37:22
明白了。
问题在于BinaryReader的构造:
StreamReader sr = new StreamReader("XXX.shb", Encoding.ASCII);
BinaryReader br = new BinaryReader(sr.BaseStream);我认为这构建了一个基于StreaReader的BinaryReader,它可以“翻译”来自文件的字符。
使用下面的代码,实际上效果很好:
FileInfo fi = new FileInfo("XXX.shb");
BinaryReader br = new BinaryReader(fi.OpenRead());我想知道是否可以使用文本流阅读器逐行读取这些类型的数据,因为行结束是在“编码”阶段保留的。
发布于 2010-03-04 06:27:19
我想你应该使用BinaryReader和ReadBytes(),然后只在交换了位之后对字节序列使用Encoding.ASCII.GetString()。
在您的示例中,您似乎将文件读取为ascii (意思是,在读取时将字节转换为.NET内部双字节代码,告诉它它是ascii),然后再次将其转换回字节,即ascii字节。
这对你来说是不必要的。
https://stackoverflow.com/questions/2375451
复制相似问题