Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,596 questions

55,330 answers

573 users

How to search a string using bitwise operators C

1 Answer

0 votes
#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

*/

 



answered 2 days ago by avibootz
...