byte[] does not equal a matching byte[], but the hex values match.

I have two byte arrays, one is 4 bytes long containing a known sequence, the other is file data. I am attempting to locate the 4-byte sequence in the file data by checking every four bytes in the file data, and using indexing to get the four bytes. Here's the code:
byte[] data = File.ReadAllBytes(fileName);
byte[] header = new byte[] { 0x4B, 0x54, 0x53, 0x52 };
int pos = 0;
for (int i = 4; i < data.Length; i += 4) {
#if DEBUG
Debug.WriteLine(Convert.ToHexString(data[pos..i]));
bool isTrue = Convert.ToHexString(data[pos..i]) == Convert.ToHexString(header); // this is true
bool isFalse = data[pos..i] == header; // this is false
#endif
if (data[pos..i] == header) {
break;
}
pos += 4;
}
byte[] data = File.ReadAllBytes(fileName);
byte[] header = new byte[] { 0x4B, 0x54, 0x53, 0x52 };
int pos = 0;
for (int i = 4; i < data.Length; i += 4) {
#if DEBUG
Debug.WriteLine(Convert.ToHexString(data[pos..i]));
bool isTrue = Convert.ToHexString(data[pos..i]) == Convert.ToHexString(header); // this is true
bool isFalse = data[pos..i] == header; // this is false
#endif
if (data[pos..i] == header) {
break;
}
pos += 4;
}
Can anyone explain this behavior? And suggest how I can fix it? Thanks
13 Replies
Kouhai
Kouhai2y ago
if (data[pos..i] == header) {
break;
}
if (data[pos..i] == header) {
break;
}
Is checking if the references are equal, not whether the contents are equal
Arch Leaders
Arch Leaders2y ago
Ah, right I think I just found another answer on StackOverflow as well, I need to use data[pos..i].SequenceEqual(header). Which lined up with your answer. Thanks
Kouhai
Kouhai2y ago
Np
Jester
Jester2y ago
@Arch Leaders i strongly recommend making a span for header and data. then use the IndexOf (does the loop and compare for you, but more optimised) method. it should be much faster than the code you wrote and allocate a million times less memory.
ero
ero2y ago
didn't .net 6 add list pattern matching or was that .net 7
Anar
Anar2y ago
7
Arch Leaders
Arch Leaders2y ago
Is it possible to read all bytes into a span?
Jester
Jester2y ago
byte[] has a .AsSpan() method
Arch Leaders
Arch Leaders2y ago
Also are you saying use IndexOf on the data instead of iterating the data? Ah okay, thanks.
Jester
Jester2y ago
so var bytes = file.readallbytes var spanoverbytes = bytes.asspan() spanoverbytes.indexof(otherspan)
Arch Leaders
Arch Leaders2y ago
What is otherspan here?
Jester
Jester2y ago
the byte array youre looking for as span
Arch Leaders
Arch Leaders2y ago
Wait that actually works? Not on my PC to test, but IndexOf will find a span of bytes at any place in another span? (The start pos of the span I’m looking for is indeterminate, all I know to is that it’s divisible by 4)