Thread: Bitwise logical Not

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User cdonlan's Avatar
    Join Date
    Sep 2004
    Posts
    49

    Bitwise logical Not

    Im trying to figure our how to perform a logical Not operation on a bit string.

    ex. from 1101001 to the negation 00101100.

    I was thinking of making an if statment for each value of the array, but this would be a lot of code. I assume there is a more efficient way to do this.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    How about this?
    Code:
    #include <stdio.h>
    
    int main(void)
    {
      char str[] = "1101001";
      int i;
    
      for(i = 0; str[i]; ++i)
        putchar('0' + !(str[i] - '0'));
      putchar('\n');
    
      return 0;
    }
    If you understand what you're doing, you're not learning anything.

  3. #3
    The C-er
    Join Date
    Mar 2004
    Posts
    192
    Use the bitwise logical not operator (~)

    e.g.
    Code:
    int notx = ~x;
    Couldn't be simpler.

    Although you talk of a "bit string" and an array - if it is encoded in a string then you would need to extract the bits first.

  4. #4
    Registered User
    Join Date
    Mar 2004
    Posts
    16
    I'm assuming it is an ASCII string that only contains '0's and/or '1's.

    Code:
    char *
    bitstrnot(char *const string)
    {
            register char   *pointer;
    
    
            for (pointer = string; *pointer != '\0'; pointer++)
                    *pointer ^= 1;
    
            return string;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Bitwise Questions
    By someprogr in forum C Programming
    Replies: 8
    Last Post: 12-14-2008, 06:45 PM
  2. Logical Operations on Bit Patterns
    By mthemapc in forum C++ Programming
    Replies: 7
    Last Post: 02-17-2008, 03:04 PM
  3. Characters into bitwise ints
    By Code Zer0 in forum C++ Programming
    Replies: 9
    Last Post: 04-24-2003, 08:34 AM
  4. Replies: 5
    Last Post: 10-30-2002, 10:23 PM
  5. Size of 1 pixel
    By ooosawaddee3 in forum C++ Programming
    Replies: 4
    Last Post: 07-26-2002, 08:06 PM