我有一個程序使用stdio接口保存一個文本文件。它將4個MSB與4個LSB交換,除了字符CR和/或LF。FileStream和編碼
我想使用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#代碼?
當處理文件爲「啞」字節時,行結束沒有任何意義,我認爲你不必在BinaryReader中支持「行讀」,但是這是否真的對你來說是一個問題?如果你仍然想要「解碼」你的整個文件,那麼逐行執行它就沒有什麼意義了。 – jishi 2010-03-04 09:20:10