Shop OBEX P1 Docs P2 Docs Learn Events
How to address bits in a Byte — Parallax Forums

How to address bits in a Byte

bsnutbsnut Posts: 521
edited 2010-11-27 08:23 in Propeller 1
Is it possible to address bits in a byte or longs in Spin?

I know how to do it with Basic Stamps and also understand may have to use the binary numbers to do what I want in Spin. Is this what, I have to do?

Comments

  • lanternfishlanternfish Posts: 366
    edited 2010-11-26 02:51
    You can use the bitwise operators similarly to Stamp BASIC. Check the posts listed below in the Similar Threads box
  • bill190bill190 Posts: 769
    edited 2010-11-26 06:26
    You can pick out a specific bit or bits with the help of left shift, right shift, AND, and the use of a "mask".

    (Using short numbers for demonstration...)
    0010 left shift would be 0100
    0010 right shift would be 0001

    Then you can pick out specific bits using AND with a "mask"...

    1011 AND with mask 0001 would be 0001
    1010 AND with mask 0001 would be 0000

    1011 AND with mask 0010 would be 0010
    1001 AND with mask 0010 would be 0000

    1011 AND with mask 1111 would be 1011

    The "mask" is whatever you want to make it. The 1's in the mask being the bits you want to pick out.
  • JonnyMacJonnyMac Posts: 9,208
    edited 2010-11-26 08:47
    I have these methods built into my standard programming template.
    pub getbit(target, pos)
    
    '' returns bit value (0..1) of target.pos
    
      return (target >> pos) & 1
    
    
    pub putbit(target, pos, value)
    
    '' writes value.0 to target.pos
    
      if (value & 1)
        return target | (1 << pos)
      else
        return target & !(1 << pos)
    
    
    pub togglebit(target, pos)
    
    '' toggles target.pos
    
      return target ^ (1 << pos)
    


    Note that when porting BASIC Stamp code to the Propeller you won't always want to use these methods, you may end up with inline code as it's more efficient (e.g., duplicating SHIFTIN or SHIFTOUT).
  • bsnutbsnut Posts: 521
    edited 2010-11-26 16:53
    Thanks Jon I can see how different it is with the Propeller.

    Is there way I can get copy of the templale you use
  • JonnyMacJonnyMac Posts: 9,208
    edited 2010-11-27 08:23
    Is there way I can get copy of the template you use

    It's attached. I prefix it with underscores to force it to the top of the files pane in the Propeller Tool -- makes it easy to find.
Sign In or Register to comment.