Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Object-Pascal / Delphi-Language (https://www.delphipraxis.net/32-object-pascal-delphi-language/)
-   -   Delphi zweitkleinste Informaionseinheit (https://www.delphipraxis.net/39731-zweitkleinste-informaionseinheit.html)

Elite-Koennen 7. Feb 2005 08:04


zweitkleinste Informaionseinheit
 
Moin.

Wollte mal um verschiedene Möglichkeiten der Bitabfrage in einem Byte (oder Integer) fragen. Suche nämlich nach einem möglichst einfachen Weg diese abzufragen und/oder zu schreiben, der auch in einer Zeile Platz findet.

Hier ein Beispiel:
Delphi-Quellcode:
// n=0 für das linke Bit
function BitIsSet(B,n : Byte):Boolean;
begin
 B:=B shl n;
 if B>127 then Result:=True else Result:=False;
end;

Muetze1 7. Feb 2005 08:11

Re: zweitkleinste Informaionseinheit
 
Moin!

Delphi-Quellcode:
// n=0 für das linke Bit
Function BitIsSet(Const B, n : Byte): Boolean;
Begin
  Result := ( ( B Shr n ) And 1 ) > 0;
End;
MfG
Muetze1

MaBuSE 7. Feb 2005 08:56

Re: zweitkleinste Informaionseinheit
 
Delphi-Quellcode:
uses Math;
...
// n=0 für das rechte Bit, n=7 für das linke Bit
function getBit(Zahl, Bit: Integer):Boolean;
begin
  Result := Zahl and Round(IntPower(2, Bit)) = Round(IntPower(2, Bit));
end;
Diese Funktion ist nicht so performant wie die von Mütze(wegen den Round und IntPower), aber das Prinzip das dahintersteht ist einfach:
Delphi-Quellcode:
Result := Zahl and  1 =  1; // True, wenn 1. Bit gesetzt ist
Result := Zahl and  2 =  2; // True, wenn 2. Bit gesetzt ist
Result := Zahl and  4 =  4; // True, wenn 3. Bit gesetzt ist
Result := Zahl and  8 =  8; // True, wenn 4. Bit gesetzt ist
Result := Zahl and 16 = 16; // True, wenn 5. Bit gesetzt ist
Result := Zahl and 32 = 32; // True, wenn 6. Bit gesetzt ist
Result := Zahl and 64 = 64; // True, wenn 7. Bit gesetzt ist
Result := Zahl and 128 = 128; // True, wenn 8. Bit gesetzt ist
Das kann man auch kombinieren
Delphi-Quellcode:
Result := Zahl and  5 =  5; // True, wenn 1. Bit und das 3. gesetzt ist (5 = 1 + 4)
Somit ist es leicht möglich mit nur einem If auf mehrere Bits abzufragen.

Mütze macht eigentlich fast das gleiche, er verschiebt nur vorher die Bits, so das das gesuchte Bit an der 1. Stelle steht, dann braucht er nur noch "and 1 = 1" zu prüfen.


Alle Zeitangaben in WEZ +1. Es ist jetzt 11:46 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz