Shop OBEX P1 Docs P2 Docs Learn Events
Getting multiple bits from variable by alias. — Parallax Forums

Getting multiple bits from variable by alias.

CuriousOneCuriousOne Posts: 931
edited 2013-07-10 10:33 in BASIC Stamp
The topic title is a bit strange, but I have no words to describe otherwise what I need.

Quote from help:
rhino   [COLOR=#000000][B]VAR[/B][/COLOR]     Word                    ' A 16-bit variable
eye     [COLOR=#000000][B]VAR[/B][/COLOR]     rhino.BIT9              ' A bit

But what if I want eye variable to be a byte, which bits start from BIT2 to BIT9 of variable rhino ?

How should I ?

Comments

  • Hal AlbachHal Albach Posts: 747
    edited 2013-07-10 05:31
    rhino     VAR     WORD
    rhino  =  rhino    >> 2
    eye      VAR     rhino.LOWBYTE
    
    If the WORD rhino has to be preserved then copy it to another WORD variable and shift that one
    rhino     VAR     WORD
    .
    .
    .
    TempRhino    =   rhino
    TempRhino  =  TempRhino    >> 2
    eye      VAR    TempRhino.LOWBYTE
    
  • Mike GreenMike Green Posts: 23,101
    edited 2013-07-10 06:23
    Hal Albach has most of it. To extract the 8 bits from bits 2..9 of a word, you'd write
    eye = (rhino >> 2) & $FF
    
    To store into a section of a word, you have to preserve the rest of the word like this
    rhino = (rhino & $FC03) | (eye << 2)
    
    In these cases, "eye" is a temporary byte variable. There is no way to declare a name for a portion of another variable except for nibbles and bytes.
  • Chris SavageChris Savage Parallax Engineering Posts: 14,406
    edited 2013-07-10 10:33
    CuriousOne wrote: »
    But what if I want eye variable to be a byte, which bits start from BIT2 to BIT9 of variable rhino ?How should I ?

    If you align the bits you want to be from 0 to 7 you could use:
    rhino   [COLOR=#000000][B]VAR[/B][/COLOR]     Word                    ' A 16-bit variable
    eye     [COLOR=#000000][B]VAR[/B][/COLOR]     rhino.lowbyte       ' Lower Byte
    

    Likewise you could use a nibble if needed for 4-bits at a time. If you really need them offset like you mentioned then you would have to do it the way Hal and Mike described.
Sign In or Register to comment.