![]() |
IsPowerOfTwo
Des öfteren möchte man testen ob eine Zahl eine Exponentation von 2 ist, zb. 1,2,4,8,16,32 usw. Dazu findet man immer wieder im WEB einen Source der so ähnlich ist wie der nachfolgende.
Delphi-Quellcode:
Aber wenn man sich ein bischen mit Boolscher Algebra auskennt weiß man das obiger Code viel zu ineffizient ist. Ich möchte hier nun zeigen wie es viel eleganter geht.
function IsPowerOfTwo(X: Cardinal): Boolean;
var I, Y : Integer; begin Y := 2; for I := 1 to 32 do begin if X = Y then begin Result := True; Exit; end; Y := Y shl 1; end; Result := False; end;
Delphi-Quellcode:
Das ist alles.
function IsPowerOfTwo(Value: Cardinal): Boolean;
begin Result := (Value > 0) and (Value and (Value -1) = 0); end; Gruß Hagen |
Alle Zeitangaben in WEZ +1. Es ist jetzt 18:47 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-2025 by Thomas Breitkreuz