## Delphi and Kylix

Moderators: pritaeas
Number of posts: 19073

This Forum Only

Access to each bit of an integer Posted by hadipardis on 18 Jun 2006 at 2:57 AM
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
Re: Access to each bit of an integer Posted by zibadian on 18 Jun 2006 at 10:07 AM
: 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:
```Bit Code
1   \$01 // Hexidecimal numbers
2   \$02
3   \$04
4   \$08
5   \$10
6   \$20
7   \$40
8   \$80
```

To access a single bit use the AND:
```  i := \$55 and \$01; // i contains least significant bit
```

To set a specific bit use the OR:
```  i := i or \$02; // i second least significant bit is set
```

Switching a bit:
```  i := i xor \$01; // the least significant bit either cleared if set
// or set if it was cleared
```

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.
```  i := i and (\$FF-\$08); // removes the 4th bit
```

## Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic