Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Access to each bit of an integer

hadipardishadipardis Posts: 134Member
How can I access to each bit in an integer type or byte? For example, suppose that we want to set the 2nd bit of a byte to 1 and first bit to zero. How can I do so? Thanks

Comments

  • zibadianzibadian Posts: 6,349Member
    : How can I access to each bit in an integer type or byte? For example, suppose that we want to set the 2nd bit of a byte to 1 and first bit to zero. How can I do so? Thanks
    :
    The quickest way is to use the logical AND, OR, XOR. OR is then used as an addition, AND as a subtraction, and XOR as a switch. Each bit is represented by its decimal code:
    [code]
    Bit Code
    1 $01 // Hexidecimal numbers
    2 $02
    3 $04
    4 $08
    5 $10
    6 $20
    7 $40
    8 $80
    [/code]
    To access a single bit use the AND:
    [code]
    i := $55 and $01; // i contains least significant bit
    [/code]
    To set a specific bit use the OR:
    [code]
    i := i or $02; // i second least significant bit is set
    [/code]
    Switching a bit:
    [code]
    i := i xor $01; // the least significant bit either cleared if set
    // or set if it was cleared
    [/code]
    To subtract a bit, use AND with the complement bit mask. The complement bit mask is all bits set, except the ones you want to clear.
    [code]
    i := i and ($FF-$08); // removes the 4th bit
    [/code]
Sign In or Register to comment.