Thread: bitwise negation

  1. #1
    Registered User
    Join Date
    Jul 2003
    Posts
    3

    bitwise negation

    hi ,

    my question is related to C 's bitwise negation (~) when i do bitwise negation to 0(zero) it gives -1 as a result . i want to how internally machine ( using 2's compliment and 1's compliment )computes can anybody please help with an example (using bit representation of number)

    thanx in advance
    Code:
    Code:
     int main() { int a=~0; printf("%s",a); }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    "The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set)."
    • In 2's complement, a value composed of all-bits-clear represents a 0.
    • In 1's complement, a value composed of all-bits-clear represents a 0.
    • In 2's complement, a value composed of all-bits-set represents a -1.
    • In 1's complement, a value composed of all-bits-set represents a -0.
    Google can also help.
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    char *bitdisp(char *dst, unsigned int value)
    {
       char *start = dst;
       unsigned int bit;
       for ( bit = ~(~0U >> 1) + 1; bit; bit >>= 1 )
       {
          *dst++ = (value & bit) ? '1' : '0';
       }
       *dst = '\0';
       return start;
    }
    
    int main ( void )
    {
       const char fmt[] = "The value represented by the bits \"%s\" is %d.\n";
       int u = 0;
       char s [ CHAR_BIT * sizeof(u) + 1 ];
       printf(fmt, bitdisp(s,u), u);
       u = ~0;
       printf(fmt, bitdisp(s,u), u);
       return 0;
    }
    
    /* my output
    The value represented by the bits "00000000000000000000000000000000" is 0.
    The value represented by the bits "11111111111111111111111111111111" is -1.
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

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. bitwise operations with double
    By henry_kay in forum C Programming
    Replies: 2
    Last Post: 10-03-2007, 04:57 AM
  3. Tough Bitwise Exercise
    By Charmy in forum C++ Programming
    Replies: 9
    Last Post: 09-08-2005, 06:27 PM
  4. bitwise negation problem
    By Mr_Jack in forum C++ Programming
    Replies: 4
    Last Post: 03-15-2004, 08:16 PM
  5. Characters into bitwise ints
    By Code Zer0 in forum C++ Programming
    Replies: 9
    Last Post: 04-24-2003, 08:34 AM