Thread: Bitwise logical Not

  1. #1
    Registered User cdonlan's Avatar
    Join Date
    Sep 2004

    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
    Oregon, USA
    How about this?
    #include <stdio.h>
    int main(void)
      char str[] = "1101001";
      int i;
      for(i = 0; str[i]; ++i)
        putchar('0' + !(str[i] - '0'));
      return 0;
    If you understand what you're doing, you're not learning anything.

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

    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
    I'm assuming it is an ASCII string that only contains '0's and/or '1's.

    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