Thread: Bitwise operators question

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    167

    Bitwise operators question

    Code:
    #include<stdio.h>
    #include<limits.h>
    
    
    int main()
    {
            unsigned char a=0;
            int i=0;
            int masca[]={0,0,1,1,1,0,0,1};
    
            for(i=CHAR_BIT-1;i>=0;i--)
            {
                    (a>>i)=(a>>i)|(masca[8-i]);
            }
    
            for(i=CHAR_BIT-1;i>=0;i--) printf("%d",(a>>i)&1);
            printf("\n");
    
            return 0;
    }
    i want to change the a to the mask. How can I do that? The code is wrong in the bolded line.

    Thank you!

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Maybe
    Code:
    a = a | ( masca[8-i] << i );
    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.

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Also, don't forget you can use the shortcut operators with bitwise operations (e.g. a = a | b; is equivalent to a |= b;)
    If you understand what you're doing, you're not learning anything.

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    21
    may be this?
    Code:
        a = (a>>i)|(masca[8-i]);

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    This?
    Code:
    #include <stdio.h>
    #include <limits.h>
    
    int main()
    {
       unsigned char a = 0;
       int i, masca[] = {0,0,1,1,1,0,0,1};
       for ( i = 0; i < CHAR_BIT; ++i )
       {
          a |= masca[i] << ((CHAR_BIT - 1) - i);
       }
       printf("a = 0x%X\n", (unsigned)a);
       return 0;
    }
    
    /* my output
    a = 0x39
    */
    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 operators
    By manzoor in forum C++ Programming
    Replies: 12
    Last Post: 08-18-2008, 02:43 PM
  2. evaluating statements with bitwise operators
    By tbabula in forum C Programming
    Replies: 1
    Last Post: 06-25-2008, 07:49 AM
  3. question about overloading operators
    By *DEAD* in forum C++ Programming
    Replies: 9
    Last Post: 05-08-2008, 10:27 AM
  4. Bitwise Operators - Setting and Retreiving a Bit
    By Spono in forum C Programming
    Replies: 2
    Last Post: 11-04-2003, 02:09 PM
  5. Question about operators.
    By Liger86 in forum C++ Programming
    Replies: 3
    Last Post: 12-30-2002, 04:00 PM