Thread: bitwise OR unexpected result

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    13

    bitwise OR unexpected result

    unsigned int a = 40;
    unsigned int mask = 1<<3;
    unsigned int b = a | mask;
    printf ("%d", b);

    I have the above code and was expecting a result of 48 for b, but I get an output of 40.

    if I use a mask of 1<<2 i.e 4, I get the right value of 44.

    what is wrong in my code?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Nothing is wrong with the code, it's your understanding of bit-wise or (or how many places << shifts).

    Code:
    a = 101000   // aka decimal 40
    m = 001000   // aka 1<<3
    1 | 1 is always 1, not 10

    Perhaps you were thinking of addition, which does propagate to the next bit.
    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
    Registered User
    Join Date
    Apr 2006
    Posts
    13
    Quote Originally Posted by Salem View Post
    Nothing is wrong with the code, it's your understanding of bit-wise or (or how many places << shifts).

    Code:
    a = 101000   // aka decimal 40
    m = 001000   // aka 1<<3
    1 | 1 is always 1, not 10

    Perhaps you were thinking of addition, which does propagate to the next bit.
    ----------

    Thanks Salem.. i was guess i was thinking hex 40.. so dumb of me. Thanks for explaining.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Just a quick one - getting unexpected result for bitwise AND
    By mondaytofriday in forum C++ Programming
    Replies: 0
    Last Post: 06-25-2013, 01:48 AM
  2. Replies: 5
    Last Post: 03-06-2012, 04:44 PM
  3. unexpected result
    By abotaha in forum C++ Programming
    Replies: 14
    Last Post: 11-17-2009, 08:32 PM
  4. No error, but the result is unexpected
    By Nimbuz in forum C Programming
    Replies: 10
    Last Post: 07-24-2009, 03:10 PM
  5. an unexpected result.
    By System_159 in forum C Programming
    Replies: 7
    Last Post: 01-22-2008, 07:05 AM

Tags for this Thread