Strange problem when trying to read data
-
18-09-2019 - |
Question
When I write:
var tagType = _reader.ReadByte();
while (tagType != 8)
{
var skip = ReadNext3Bytes() + 11;
_reader.BaseStream.Position += skip;
tagType = _reader.ReadByte();
}
...it's working, but when I write:
var tagType = _reader.ReadByte();
while (tagType != 8)
{
_reader.BaseStream.Position += ReadNext3Bytes() + 11;
tagType = _reader.ReadByte();
}
...it is not working, and I can't understand why - I'm getting unexpected results. Heres the ReadNext3Bytes
method:
private long ReadNext3Bytes()
{
try
{
return Math.Abs((_reader.ReadByte() & 0xFF) * 256 * 256 + (_reader.ReadByte() & 0xFF)
* 256 + (_reader.ReadByte() & 0xFF));
}
catch
{
return 0;
}
}
Why is that, and how can I fix it?
Thanks.
Solution
It happens since Position is changed during ReadByte call, what you see is similar to this case:
int position = 1;
position += (position = 2) + 3;
Assert.AreEqual(6, position);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow