Page 1 of 1

How to find a binary string in binary string

Posted: Mon Mar 16, 2009 11:01 pm
by junkoi
Hi,

I am programming in C, and I want to find (the position of) a binary string in another binary string. Normally strstr() can be used, but it fails here because it can only use with a null-terminated-string.

So is there any available C function/library for this? Or we can find some implementations doing this somewhere?

(I am on Linux, using gcc and glibc)

Thanks,
Jun

Re: How to find a binary string in binary string

Posted: Mon Mar 16, 2009 11:46 pm
by Solar
No, you'll have to code it yourself. I'd start with memchr() looking for the first charakter of string 1 in string 2, aborting if the character is not found or so far back in string 2 that a complete match is no longer possible, and if everything is OK, run memcmp() on the returned address. That's assuming you have some way of determining the size of your binary strings...

Re: How to find a binary string in binary string

Posted: Tue Mar 17, 2009 8:06 am
by Hyperdrive
junkoi wrote:I am programming in C, and I want to find (the position of) a binary string in another binary string. Normally strstr() can be used, but it fails here because it can only use with a null-terminated-string.

So is there any available C function/library for this? Or we can find some implementations doing this somewhere?
I don't know if there is some C library containing the functionality you ask for. But there are many string matching algorithms out there. A famous one is Knuth-Morris-Pratt. Maybe that helps you to get started.

--TS