Shop OBEX P1 Docs P2 Docs Learn Events
setting a bit — Parallax Forums

setting a bit

TCTC Posts: 1,019
edited 2013-04-20 19:19 in Propeller 1
Hello all, I have been trying to find an easy way of setting one bit of a variable.
For example:
to read; Bit 15 = 0. To write, bit 15 = 1.

Thanks for your help

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2013-04-20 14:04
    variable |= |< bitNumber ' this sets a bit

    variable &= ! |< bitNumber ' this clears a bit

    There are longer solutions when you want to change several bits, but these are the most compact single bit methods.
  • TCTC Posts: 1,019
    edited 2013-04-20 14:08
    Wonderful, Thank You
  • TCTC Posts: 1,019
    edited 2013-04-20 14:10
    This will work great. I only have to set one bit.

    Thank You
  • TCTC Posts: 1,019
    edited 2013-04-20 14:10
    This will work great. I only have to set one bit.

    Thank You
  • JonnyMacJonnyMac Posts: 9,107
    edited 2013-04-20 19:19
    In my standard template I have these methods:
    pub rd_bit(target, pos)
    
    '' returns bit value (0..1) of target.pos
    
      if ((pos => 0) and (pos =< 31))
        return (target >> pos) & 1
      else
        return 0
    
    
    pub wr_bit(target, pos, value)
    
    '' writes value.0 to target.pos
    
      if (value & 1)
        return target | (1 << pos)
      else
        return target & !(1 << pos)
    
    
    pub toggle_bit(target, pos)
    
    '' toggles target.pos
    
      return target ^ (1 << pos)
    
Sign In or Register to comment.