3

I've a program written in C++ to read binary files. And I'm writing the same program in C#. But in some cases C# is generating wrong byte.

C++ Code

ifstream s(argv[1], fstream::binary);
unsigned char b;
while(s.good())
{
     s >> b;
     //...
     //Some other code
}

C++ runs fine.

Equivalent C# Code

BinaryReader br = new BinaryReader(new FileStream("filename.bat", FileMode.Open));
byte b;
while(br.BaseStream.Position != br.BaseStream.Length && br.BaseStream.CanRead)
{
     b = br.ReadByte();
     //...
     // some other code
}

Some values of C# are not the same as C++ Please help thank you.

Teh Sunn Liu
  • 487
  • 2
  • 14
  • Is a char in C++ still one byte or did they move to newer grounds? – rene Feb 04 '17 at 09:26
  • @rene Of course it is. – Mario Feb 04 '17 at 09:27
  • 1
    You should possibly add the actual char values you're getting from reading the file in both cases. Any chance you're just confusing signed/unsigned values? – Mario Feb 04 '17 at 09:28
  • 1
    _"C++ runs fine."_ I've got doubts: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – πάντα ῥεῖ Feb 04 '17 at 09:28
  • @rene It is one byte by definition in C++, but 1 byte doesn't have to be 8 bits. – juanchopanza Feb 04 '17 at 09:34
  • @juanchopanza yeah, I just read-up on the specs after the first comment of Mario. I'm not a C++ guy so allow me to make stupid comments. :) Thanks. – rene Feb 04 '17 at 09:35
  • The cr and lf are probably different between operating systems. The file is a bat file which has ascii characters that are handled different in windows than linux. – jdweng Feb 04 '17 at 09:52
  • how are you verifying two values? are you printing them to some file or debug output? or using debuggers watch to compare the values. Please do share your output generation code too. – A.B. Feb 04 '17 at 10:19
  • I do not think the problem is due to signed/unsigned values, byte in C# is unsigned 8-bit value, and the corresponding type in C++ is unsigned char. We would like to look into your values comparison mechanism. – A.B. Feb 04 '17 at 10:22
  • 1
    Sorry for such late reply.. But the problem wasn't with br.ReadByte(); there were some more lines after br.ReadByte(); which was reading wrong number of bytes. Thank you everybody. – Teh Sunn Liu Mar 13 '17 at 05:42

0 Answers0