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
Kouhai3y 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 LeadersOP3y 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
Kouhai3y ago
Np
Jester
Jester3y 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
ero3y ago
didn't .net 6 add list pattern matching or was that .net 7
Anar
Anar3y ago
7
Arch Leaders
Arch LeadersOP3y ago
Is it possible to read all bytes into a span?
Jester
Jester3y ago
byte[] has a .AsSpan() method
Arch Leaders
Arch LeadersOP3y ago
Also are you saying use IndexOf on the data instead of iterating the data? Ah okay, thanks.
Jester
Jester3y ago
so var bytes = file.readallbytes var spanoverbytes = bytes.asspan() spanoverbytes.indexof(otherspan)
Arch Leaders
Arch LeadersOP3y ago
What is otherspan here?
Jester
Jester3y ago
the byte array youre looking for as span
Arch Leaders
Arch LeadersOP3y 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)

Did you find this page helpful?