Skip to content

Instantly share code, notes, and snippets.

@sebingel
Last active March 16, 2021 22:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sebingel/447e2b86be27f6172bfe395b52d05c96 to your computer and use it in GitHub Desktop.
Save sebingel/447e2b86be27f6172bfe395b52d05c96 to your computer and use it in GitHub Desktop.
Compare two streams bit by bit in C#
private bool StreamEquals(Stream a, Stream b)
{
if (a == b)
{
return true;
}
if (a == null || b == null)
{
throw new ArgumentNullException(a == null ? "a" : "b");
}
if (a.Length != b.Length)
{
return false;
}
for (int i = 0; i < a.Length; i++)
{
int aByte = a.ReadByte();
int bByte = b.ReadByte();
if (aByte.CompareTo(bByte) != 0)
{
return false;
}
}
return true;
}
public static class StreamExtensions
{
public static bool StreamEquals(this Stream self, Stream other)
{
if (self == other)
{
return true;
}
if (self == null || other == null)
{
throw new ArgumentNullException(self == null ? "self" : "other");
}
if (self.Length != other.Length)
{
return false;
}
for (int i = 0; i < self.Length; i++)
{
int aByte = self.ReadByte();
int bByte = other.ReadByte();
if (aByte.CompareTo(bByte) != 0)
{
return false;
}
}
return true;
}
}
@AssafTzurEl
Copy link

Nice, but you forgot the case where a and b reference the same stream. In this case, you have a bug on your hands in lines 20-21...

I suggest you repalce lines 3-4 (comparing both to null) with:
if (a == b)
This way, if both are null or both reference the same stream object, you're good.

@AssafTzurEl
Copy link

One more comment: Call it Equals. "Compare" means it should be able to tell whether one of the stream is "less than" or "greater than" the other. See int.CompareTo vs. int.Equals, for example.

@sebingel
Copy link
Author

Nice, but you forgot the case where a and b reference the same stream. In this case, you have a bug on your hands in lines 20-21...

I suggest you repalce lines 3-4 (comparing both to null) with:
if (a == b)
This way, if both are null or both reference the same stream object, you're good.

Thank you. You are absolutely right. Gonna change it right now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment