Difference between revisions of "And"

From Lazarus wiki
Jump to navigationJump to search
Line 29: Line 29:
 
Bitwise and sets a bit to 1 if and only if all of the corresponding bits in its operands are 1.
 
Bitwise and sets a bit to 1 if and only if all of the corresponding bits in its operands are 1.
  
== Clear a bit ==
+
== Is power of two ==
  
 
<delphi>
 
<delphi>
function ClearBit(const AValue, ABitNumber:integer):integer;
+
function IsPowerOfTwo( const aValue : longint ): boolean;
 +
var
 +
  x : longint;
 +
  b : boolean;
 
begin
 
begin
  result := AValue and not(1 shl ABitNumber);
+
  b := false;
end;
+
  if aValue <> 0 then
 +
    begin
 +
      x := aValue - 1;
 +
      x := x and aValue;
 +
      if x = 0 then b := true;
 +
    end;
 +
  result := b;
 +
end;
 
</delphi>
 
</delphi>
If you call ClearBit(%1111,1) then get %1101 (%1111 = 15 and %1101 = 13). If you call ClearBit(13,2) then get 9 (9 = %1001) .
+
 
 +
If you call IsPowerOfTwo(4) then get true. If you call IsPowerOfTwo(5) then get false .
  
 
=== Read more ===
 
=== Read more ===
Line 46: Line 57:
 
* [[Function]]
 
* [[Function]]
 
* [[Integer]]
 
* [[Integer]]
 +
 +
* [[Shl# Clear a bit|Clear a bit]]

Revision as of 15:42, 12 January 2009

Deutsch (de) English (en) español (es) suomi (fi) français (fr) русский (ru)

Boolean operation

And produces a value of true if and only if both of its operands are true.

Truth table

A B   A and B  
  false     false     false
  false   true   false
  true   false   false
  true   true   true


Bitwise operation

Bitwise and sets a bit to 1 if and only if all of the corresponding bits in its operands are 1.

Is power of two

<delphi> function IsPowerOfTwo( const aValue : longint ): boolean; var

 x : longint;
 b : boolean;

begin

 b := false;
 if aValue <> 0 then
   begin
     x := aValue - 1;
     x := x and aValue;
     if x = 0 then b := true;
   end;
 result := b;

end; </delphi>

If you call IsPowerOfTwo(4) then get true. If you call IsPowerOfTwo(5) then get false .

Read more