Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

state of bit test 1

Status
Not open for further replies.

MerryMadDad

Programmer
Dec 11, 2001
47
GB
Hello,

I am trying to test the state of bits in a byte, active low state I used the case of statement
case of
254: do something
253: do something else
251:
247: and so on

The problem is without working out every possible combination, how can I detect that two bits are active at the same time ?

in assembly language I could clear the carry bit and rotate all the bits left or right and branch on the state of the carry bit, can I do something similar in Delphi pascal ? I am using Delphi 4.00 at the moment.

any help much appreciated Thanks in advance.
MMD
 
The following function returns the number of bits set in a byte:
Code:
function CountSetBitsInByte ( b: byte ): integer;
var
  eight: integer;
begin
  result := 0;
  for eight := 1 to 8 do begin
    if b and 1 = 1 then
      inc ( result );
    b := b shr 1;
  end;
end;
Hope that helps.

Andrew
 
Hi Andrew, thanks very much for that, it is just what I am looking for

Best regards

Robert
 
The following code is simpler and will probably run a bit quicker but I haven't timed it to make sure. It returns true if the byte has multiple bits and false if not.
Code:
function HasMultipleBitsSetInByte ( b: byte ): boolean;
begin
  result := not ( b in [ 0, 1, 2, 4, 8, 16, 32, 64, 128 ] );
end;

Andrew

 
sorry for off-topic question towerbase, but how do you compare different programs to find out which one is quicker?
 
Start a new topic if you want answers to this question.

Andrew
 
Hello All,

I just found out that TurboPower's systools has an StBits program that can "twiddle" the state of bits in a byte and presumably read them too. Available free from (search for TurboPower) along with loads of other tools and components etc.

For anyone thats interested

Regards

MMD
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top