milnuts milnuts - 2 months ago 7
C# Question

If condition not evaluating as expected

I'm new to Visual Studio and C#, but my problem seems almost elementary, yet I can't figure it out. I have a binary file I'm reading in and I'm trying to process it more or less a byte at a time. The problem is that when I get several bytes in my 'if' condition seems to evaluate to TRUE long after it should be FALSE.

Here's the quick jist of the input binary so the code below makes sense.


bytes[0-3]: preamble

bytes[4]: message type

bytes[5-7]: message length

bytes[8-11]: test ID



And a snippet of the code

file = openFileDialog1.FileName;
int byteLoc = 0;
try
{
var bytes = File.ReadAllBytes(file);
//loop through each byte from the input file
foreach (var singleByte in bytes)
{
//Preamble - 4 bytes
if (byteLoc < 4)
{
preamble += Convert.ToString(singleByte);
preamble += " ";
}
//Message Type - 1 byte
else if (byteLoc == 4)
{
msgType += Convert.ToString(singleByte);
}
//Message Length - 3 bytes
else if ((byteLoc > 4) || (byteLoc <= 7))
{
msgLen += Convert.ToString(singleByte);
Console.WriteLine("Len:" + byteLoc); //for debug
}
//Test ID - 4 bytes
else if ((byteLoc >= 8) || (byteLoc <= 11))
{
testID += Convert.ToString(singleByte);
Console.WriteLine("ID:" + byteLoc); //for debug
}
byteLoc++;
}
}


I have printed out the preamble and the msgType and they appear as expected. However, the problem is that when I get to the 'if' condition for the msgLen (which should be bytes 5-7), it ALWAYS evaluates to TRUE. I see the message "Len: byteLoc" starting at 5 and going all the way to the end of the file. What am I doing wrong here that the when byteLoc gets to 8, its not going to the next 'if' condition?

Answer

As mentioned the issue is that you are using || (OR) instead of && (AND) but since you're doing else if you know the previous conditions are false so you can just use upper bound checks only.

if (byteLoc < 4)
{
    preamble += Convert.ToString(singleByte);
    preamble += " ";                        
}
//Message Type - 1 byte
else if (byteLoc == 4)
{
    msgType += Convert.ToString(singleByte);
}
//Message Length - 3 bytes
else if (byteLoc <= 7)
{
    msgLen += Convert.ToString(singleByte);
    Console.WriteLine("Len:" + byteLoc);  //for debug
}
//Test ID - 4 bytes
else if (byteLoc <= 11)
{
    testID += Convert.ToString(singleByte);
    Console.WriteLine("ID:" + byteLoc);   //for debug
}
Comments