#include <stdio.h>
#include <string.h>
/*
This function searches for a substring inside a string using bitwise operations.
The comparison method:
- Two characters are equal when (a ^ b) == 0
- XOR is a fast bitwise operator, so it is used to compare characters directly.
- The function slides over the main string and checks each position.
*/
int contains_using_bitwise(const char *text, const char *pattern) {
size_t text_len = strlen(text);
size_t pat_len = strlen(pattern);
/* If the pattern is longer than the text, it cannot be found */
if (pat_len > text_len) return 0;
/* Try each possible starting position */
for (size_t i = 0; i <= text_len - pat_len; ++i) {
int match = 1; /* assume match until proven otherwise */
/* Compare characters using XOR */
for (size_t j = 0; j < pat_len; ++j) {
if ((text[i + j] ^ pattern[j]) != 0) {
match = 0;
break; /* mismatch found, stop checking this position */
}
}
/* If all characters matched, return success */
if (match) return 1;
}
/* No match found */
return 0;
}
int main(void) {
const char *text = "Hello world, bitwise search!";
const char *pattern = "bitwise";
int found = contains_using_bitwise(text, pattern);
printf("Text: %s\n", text);
printf("Pattern: %s\n", pattern);
printf("Found: %s\n", found ? "yes" : "no");
return 0;
}
/*
run:
Text: Hello world, bitwise search!
Pattern: bitwise
Found: yes
*/