FileStream and Encoding

I have a program for writing a text file using the stdio interface. It replaces 4 MSBs with 4 LSBs, with the exception of CR and / or LF characters.

I am trying to "decode" this stream using a C # program, but I cannot get the original bytes.

        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);

I tried to change the encoding in UTF8, but that didn't work. I also used a BinaryReader created using the 'sr' StreamReader, but nothing good happened.

     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);

If the file starts with 0xF2 0xF2 ..., I read everything except the expected value. Where is the mistake? (i.e.: 0xF6 0xF6).

This C code actually does the job:

            ...
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);

What is wrong with C # code?

+3
source share
2 answers

Got it.

BinaryReader:

StreamReader sr = new StreamReader("XXX.shb", Encoding.ASCII);
BinaryReader br = new BinaryReader(sr.BaseStream);

, BinaryReader StreaReader, "" , .

:

FileInfo fi = new FileInfo("XXX.shb");
BinaryReader br = new BinaryReader(fi.OpenRead());

, , "".

+2

, BinaryReader ReadBytes(), Encoding.ASCII.GetString() bytesequence , .

, , ascii ( , .NET, , ascii), , ascii- .

.

0

Source: https://habr.com/ru/post/1735340/


All Articles