Counting Bits
Geschrieben von: Peter Hellinger Donnerstag, den 25. Januar 2007 um 23:07 Uhr
As seen before in “A little bit of Bits” bit manipulation is an easy job, if you treat the bits as a set. Now I will show you a function, that will count the number of Bits (or Elements) in a given variable. Look at the Bits article for definition of the bitsets.In this function we use a special pascal feature, the "anonymous parameter". The parameter setvar is declared without any type. In fact, when we call the function we can put any variable on this place - not only a set for example, but we need to know the concrete size in bytes of the parameter to avoid reading outside the variable.
To inner restrictions of the function, the size of the variable is limited to 256 Bit (the maximum size for a set). If you need more, make the type TBitArray bigger.
function CountBits (CONST setvar; size: Integer): Integer;
// First we declare an array of Bitsets:
type TBitArray = array [0..31] of TByteBits;
// We set it on top of setvar
var bits: TBitArray absolute setvar;
i, c: Integer; // counting cariables
b: Bits;
begin
c:= 0; // start value for number of bits
// count the number of bytes
for i:= 0 to size - 1 do begin
// for each byte count the number of bits
for b:= Bit0 to Bit7 do begin
if b in bits[i] then Inc (c);
end;
end;
Result:= c;
end;
| Zurück: A litte bit of bits... | Weiter: Convert numbers to strings |
|---|











You may feel disappointed somehow, as most of my pages are written in German. And it’s true, they should be understandable to much more people than they are now. Well, the truth is, I would provide two versions if I had the time to maintain both of them…