Thread: String comparison using bitwise logic?

  1. #1
    Registered User
    Join Date
    Jan 2022
    Posts
    7

    Question String comparison using bitwise logic?

    How do you use bitwise logic to compare char *?

    char *a = "car";
    char *b = "carb";
    char *c = "";

    //bitwise logic
    //if a equals b print "yes"

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    It sounds like you just want to do something like what strcmp does to produce a yes/no result concerning the question of whether the strings are equal. If so, then it could be as simple as:
    Code:
    const char *a = "car";
    const char *b = "carb";
    if (strcmp(a, b) == 0)
    {
        puts("yes");
    }
    else
    {
        puts("no");
    }
    If not, then you need to explain what is this "bitwise logic" and why do you want to use it to "compare char *".
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jan 2022
    Posts
    7

    Why?

    I just don't want to use any built-in functions. Also, want to learn something.

    Otherwise, I can just use if (a == b).

  4. #4
    Registered User
    Join Date
    Oct 2019
    Posts
    82
    Quote Originally Posted by tibegato View Post
    I just don't want to use any built-in functions. Also, want to learn something.

    Otherwise, I can just use if (a == b).
    No, that way you would be comparing pointers. A pointer is equal to the other point if they point to the same memory location.

    Ha! I quickly put together an implementation of strcmp that even I do not have a very clear idea of how it works o.O

    Code:
    include <stdio.h>
    
    
    int strcmp(const char *a, const char *b)
    {
        while(*a++ == *b++)
    
    
        return *a - *b;
    }
    
    
    int main(int argc, char *argv)
    {
        char *first = "Carb";
        char *second = "Carb";
    
    
        if (strcmp(first, second) == 0)
        {
            printf("Equal\n");
        }else
        {
            printf("Not equal\n");
        }
    
    
        return 0;
    }
    I'm honestly not sure how the the while condition gets evaluated such that the loop comes to an end at the end of the string(s). Butt, it seems to work.

    (Probably not the best of answers there could be, but I contributed to this thread too hoping to learn).
    Last edited by ghoul; 04-11-2022 at 11:13 AM.

  5. #5
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    ghoul's strcmp implementation is doubly wrong!
    Firstly, due to a (presumably) missing semicolon, it's actually this:
    Code:
        while (*a++ == *b++)
            return *a - *b;
        // missing return statement if the while loop fails the first test
    Presumably he meant this:
    Code:
        while (*a++ == *b++) ;
        return *a - *b;
    But this is still wrong.

    What happens if *a != *b in the while test? The loop exits but the *a - *b is showing the difference between the NEXT bytes, not the ones that stopped the while loop. If those bytes just happen to be equal, it will return 0, indicating that the strings are equal.

    If the strings are equal then the test will run off the end after comparing *a == *b for when they are both the terminating '\0'. then the *a - *b will subtract the two bytes after the '\0' even though those are not part of the strings!

    @tibegato, comparing the strings "bitwise", although doable, would be totally retarded.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  6. #6
    Registered User
    Join Date
    Jan 2022
    Posts
    7

    Ok

    First off thank you, for your corrections on the code sample. You are correct.

    Second, no one asked if comparing strings using bitwise operators was good or bad. Just want to know how. Presenting the code to do it and appending a note saying that it's really inefficient or something would've been a better approach.

    Quote Originally Posted by john.c View Post
    ghoul's strcmp implementation is doubly wrong!
    Firstly, due to a (presumably) missing semicolon, it's actually this:
    Code:
        while (*a++ == *b++)
            return *a - *b;
        // missing return statement if the while loop fails the first test
    Presumably he meant this:
    Code:
        while (*a++ == *b++) ;
        return *a - *b;
    But this is still wrong.

    What happens if *a != *b in the while test? The loop exits but the *a - *b is showing the difference between the NEXT bytes, not the ones that stopped the while loop. If those bytes just happen to be equal, it will return 0, indicating that the strings are equal.

    If the strings are equal then the test will run off the end after comparing *a == *b for when they are both the terminating '\0'. then the *a - *b will subtract the two bytes after the '\0' even though those are not part of the strings!

    @tibegato, comparing the strings "bitwise", although doable, would be totally retarded.

  7. #7
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    It's beyond inefficient. It's literally retarded. That's why I used the technical term. Why should I waste my time writing ridiculously simple and pointless code for you?
    A little inaccuracy saves tons of explanation. - H.H. Munro

  8. #8
    Registered User
    Join Date
    Jan 2022
    Posts
    7

    Cause

    I asked ... for learning purposes.

    There's millions of things we learn, we don't actually use. I saw a post were you could toggle case of a string with a bitwise operation:

    https://www.geeksforgeeks.org/toggle...ise-operators/

    Would you ever do that ... probably not.

    Quote Originally Posted by john.c View Post
    It's beyond inefficient. It's literally retarded. That's why I used the technical term. Why should I waste my time writing ridiculously simple and pointless code for you?

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Perhaps you could use the fact that xoring a number with itself is zero.

    So comparing the first char of each string would be
    if ( (*a ^ *b) == 0 )

    while loops and stopping at \0 are as per usual for the task.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    I suggest that you learn to use the standard library and perhaps other common utility libraries before you go along the path of the obscure. After you learn to use them, learn to implement them.

    I mean, you didn't even know that strcmp is not the same as directing comparing pointers to char with the == operator. Have you ever implemented strcmp or something like it? If you have not yet acquired such foundational knowledge, why attempt "comparing strings using bitwise operators"? Learn the basics, then doing the esoteric will be much easier.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Perhaps it was a homework assignment from an unqualified instructor, a bad book, painfully inadequate online tutorial, YouTube video, ... If so, it should never been assigned, or listed.

  12. #12
    Registered User
    Join Date
    Oct 2019
    Posts
    82
    Speaking of which, may be I'm hijacking this thread at this point.

    My finer implementation works but chokes on NULL....

    Code:
    int strCmp(const char *s1, const char *s2 )
    {
            const char *p1 = s1;
            const char *p2 = s2;
    
    
            while (*p1 == *p2)
            {
                    if (*p1 == '\0')
                            return *p1 - *p2;
                    p1++;
                    p2++;
            }
    
    
            return *p1 - *p2;
    }

  13. #13
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    Quote Originally Posted by ghoul View Post
    Speaking of which, may be I'm hijacking this thread at this point.

    My finer implementation works but chokes on NULL....

    Code:
    int strCmp(const char *s1, const char *s2 )
    {
            const char *p1 = s1;
            const char *p2 = s2;
    
    
            while (*p1 == *p2)
            {
                    if (*p1 == '\0')
                            return *p1 - *p2;
                    p1++;
                    p2++;
            }
    
    
            return *p1 - *p2;
    }
    It's fine if it chokes on NULL. The standard strcmp requires non-null arguments and is not guaranteed to work if one or both arguments are null (in fact, the behavior is undefined in those cases).

    Also, the first return *p1 - *p2; line could be changed to return 0; (since we know the characters are the same at that point) or to break;.

  14. #14
    Registered User
    Join Date
    Dec 2017
    Posts
    1,628
    Code:
    int my_strcmp(const char *a, const char *b)
    {
        while (*a && *a == *b) ++a, ++b;
        return (unsigned char)*a - (unsigned char)*b;
    }
    Note the conversion to unsigned char (if they weren't already unsigned) for the subtraction.
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. std::string comparison versus int comparison
    By leeor_net in forum C++ Programming
    Replies: 3
    Last Post: 04-12-2009, 07:28 AM
  2. String Comparison
    By kpreston in forum C Programming
    Replies: 16
    Last Post: 10-20-2008, 07:43 PM
  3. string comparison
    By sj999 in forum C Programming
    Replies: 4
    Last Post: 05-23-2008, 03:10 AM
  4. please help with a string comparison.
    By MegaManZZ in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 01:33 PM
  5. Bitwise & logic operations...
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 11-26-2001, 08:18 PM

Tags for this Thread