Shop OBEX P1 Docs P2 Docs Learn Events
Setting bits through a mask — Parallax Forums

Setting bits through a mask

ErlendErlend Posts: 612
edited 2014-11-29 14:33 in Propeller 1
I know how to read one particular bit out from a Long - and maybe I knew how to set one particular bit in a Long, but I don't any longer - I just get messed up in repeat >>'s and stuff, not very elegant. I feel stupid.
What is the equvalent of bitvalue:= longvalue AND bitmask - when I want to set the bit instead of reading it? Is there a BITSET (longvalue, bitmask, bitvalue)?

This is so embarresing - it is probably there, right under my nose.

Erlend

Comments

  • SapphireSapphire Posts: 496
    edited 2014-11-29 10:35
    longvalue |= bitmask will set bitmask in longvalue.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2014-11-29 10:45
    What you want is this:
    longvalue := (longvalue & !bitmask) | (bitvalue & bitmask)

    BTW, the parens are unnecessary for the compiler; they just make the order of operation clearer to us humans.

    -Phil
  • JonnyMacJonnyMac Posts: 9,105
    edited 2014-11-29 13:39
    I use this little method in several programs.
    pub wr_bit(target, pos, value)
    
    '' writes value.0 to target.pos
    
      if (value & 1)
        return target | (1 << pos)
      else
        return target & !(1 << pos)
    


    By passing a value instead of a pointer, I can modify a variable like this:
    someValue := wr_bit(someValue, 0, 0)
    


    or update a different variable with a modification
    anotherValue := wr_bit(someValue, 0, 1)
    
  • ErlendErlend Posts: 612
    edited 2014-11-29 14:33
    Within few hours I get two methods, one ideal for setting one bit, one ideal for setting one or more bits. Very nice addition to my toolbox. Without this forum I would have been nothing in this game. Without you guys this forum would have been nothing.
    (and there is no smirk-smirk here, like in there are in so many other forums)

    Erlend
    btw, checking out method 1 brought me back to the days of Karnough diagrams...
Sign In or Register to comment.