Thread: Bit puzzeling

  1. #1
    Registered User
    Join Date
    May 2011
    Location
    Sweden
    Posts
    24

    Bit puzzeling

    Hi!

    I am looking for a good way of assigning a specific bit in a variable the value of a specific bit in another variable.

    For example bit 2 in variable a = bit 5 in variable b.

    Any suggestions?


    //John

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Maybe not the best way, but:
    Code:
        unsigned a = 0x00, b = 0xff;
        int abit  = 2, bbit = 5;
    
        if (b & (1 << bbit))
            a |= (1 << abit);
        else
            a &= -1 ^ (1 << abit);

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    -1 ^ is a curious way of saying ~

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Quote Originally Posted by nonoob View Post
    -1 ^ is a curious way of saying ~
    Thanks nonoob. I thought that part looked weird. I don't twiddle bits very often, hence "maybe not the best way". This looks much better:
    Code:
        unsigned a = 0x00, b = 0xff;
        int abit  = 2, bbit = 5;
    
        if (b & (1 << bbit))
            a |= (1 << abit);
        else
            a &= ~(1 << abit);

  5. #5
    Registered User
    Join Date
    May 2011
    Location
    Sweden
    Posts
    24
    Thanks for helping!

Popular pages Recent additions subscribe to a feed