Shop OBEX P1 Docs P2 Docs Learn Events
best method to extract and compare single bits? — Parallax Forums

best method to extract and compare single bits?

Jimmy W.Jimmy W. Posts: 112
edited 2008-07-05 03:12 in Propeller 1
What is everyone using to extract single bits from longs? I know they were some talks of using ctrb and whatnot, I am currently unhappy with the way I have been doing it for a while now, shift left till the bit is MSB then right shift it to LSB then compare against 1, it is a very inefficient process and I am looking to squeeze a bit more speed out of these comparisons.

Forgot to mention, this is in spin, thanks!

Thanks, and happy 4th!

Jimmy

Post Edited (Jimmy W.) : 7/5/2008 2:54:48 AM GMT

Comments

  • stevenmess2004stevenmess2004 Posts: 1,102
    edited 2008-07-05 01:25
    You can use the test instruction with wz something like this
    mov x,#123
    test x,testBit wz
    'code to use the bit...
    
    testBit long %0010
    
    



    The test instruction is simply an and that doesn't write the result.
  • Jimmy W.Jimmy W. Posts: 112
    edited 2008-07-05 01:32
    I should have been more specific when talking about a chip that you can write high level or low level code for. I am using this test in spin [noparse]:)[/noparse]
  • hippyhippy Posts: 1,981
    edited 2008-07-05 03:08
    I'm not entirely clear what your exact situation is but if you want to check or use bit N (0 to 31) I'd use ...

      ' Test if bit N is set or clear
    
      if longVar & ( |< N )
        BitIsSet
      else
        BitIsClear
    
      ' Optimised when N is a constant
    
      if longVar  & constant( |< N )
        BitIsSet
      else
        BitIsClear
    
      ' To get bit N ( as a 0 or 1 )
    
      result := ( longVar >> N ) & 1
    
    
    
  • stevenmess2004stevenmess2004 Posts: 1,102
    edited 2008-07-05 03:12
    What you've got is probably about the most efficient. Something like one of the following
    bit:=(var>>bitNumber)&1
    

    or
    if var&|<bitNumber
    


    Don't know which is quicker. If it was always the same value you could use a precalculated value instead which may speed things up. If speed is marginal there are a couple of things you can do such as making sure the two variables are in either the first 8 object variables or the the first 7 method variables. Also, if possible keep any constants small so that they will fit in a byte or word rather than a long which will also make it slightly faster (there's three less hub accesses needed for a byte than a long constant in spin).
Sign In or Register to comment.