![]() |
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; |
Re: zweitkleinste Informaionseinheit
Moin!
Delphi-Quellcode:
MfG
// n=0 für das linke Bit
Function BitIsSet(Const B, n : Byte): Boolean; Begin Result := ( ( B Shr n ) And 1 ) > 0; End; Muetze1 |
Re: zweitkleinste Informaionseinheit
Delphi-Quellcode:
Diese Funktion ist nicht so performant wie die von Mütze(wegen den Round und IntPower), aber das Prinzip das dahintersteht ist einfach:
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;
Delphi-Quellcode:
Das kann man auch kombinieren
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
Delphi-Quellcode:
Somit ist es leicht möglich mit nur einem If auf mehrere Bits abzufragen.
Result := Zahl and 5 = 5; // True, wenn 1. Bit und das 3. gesetzt ist (5 = 1 + 4)
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:50 Uhr. |
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz