1,105,221 Community Members

Generating a bitwise AND filter.

Member Avatar
davecoventry
Junior Poster in Training
61 posts since Jun 2009
Reputation Points: 8 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 1 [?]
 
0
 

Depending on a variable 1-7, I am interested in ANDing a byte value to to get that number of bits.

Currently I'm doing this:

function getMaskedBits(num, Bit_location: Byte): Byte;
var
  masks: array[1..7]of Byte=(127,63,31,15,7,3,1);
begin
  Result:=num and masks[Bit_location];
end;

is there a better (or more efficient way of doing this?)

Member Avatar
pritaeas
mod_pritaeas
11,301 posts since Jul 2006
Reputation Points: 1,420 [?]
Q&As Helped to Solve: 1,833 [?]
Skill Endorsements: 155 [?]
Moderator
Featured
Sponsor
 
0
 

This works just fine.

You can probably also use something like this:

Result := num and (127 shr (bit_location - 1));
Member Avatar
davecoventry
Junior Poster in Training
61 posts since Jun 2009
Reputation Points: 8 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 1 [?]
 
0
 

Sorry for not replying earlier: Thanks very much for your help!

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article