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:
Can anyone explain this behavior? And suggest how I can fix it?
Thanks
13 Replies
Is checking if the references are equal, not whether the contents are equal
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.
ThanksNp
@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.
didn't .net 6 add list pattern matching
or was that .net 7
7
Is it possible to read all bytes into a span?
byte[] has a .AsSpan() method
Also are you saying use IndexOf on the data instead of iterating the data?
Ah okay, thanks.
so
var bytes = file.readallbytes
var spanoverbytes = bytes.asspan()
spanoverbytes.indexof(otherspan)
What is otherspan here?
the byte array youre looking for
as span
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)