One byte has eight digits, which may be 0 or 1; now we need to calculate the total number of digits in one byte.
The first method is a function;
The second method is stupid. It is to first assign the 256 possible values to an array and retrieve them at any time.
Although the first method is clever, it is not as fast as the second method (in the author's book, it is generally about 10 times faster in non-special cases );
The second method is fast and easy to use, but at the cost of 256 bytes of array space.
Unit unit1; interfaceuses windows, messages, extensions, variants, classes, graphics, controls, forms, dialogs, stdctrls; Type tform1 = Class (tform) button1: tbutton; Procedure button1click (Sender: tobject); end; var form1: tform1; implementation {$ R *. DFM} {Method 1: Obtain function} function getbytebits (X: byte): byte; begin result: = 0; while x 0 do begin if odd (X) then Inc (result); X: = x SHR 1; end; {Method 2: Place all possible values in a constant array} const bitarr: array [0 .. maxbyte] of byte =,,,,,, 5, 6, 5, 6, 6, 6, 4, 5, 5, 6, 6, 6, 6, 6, 6, 7, 8); {test} procedure tform1.button1click (Sender: tobject); var B, num: byte; begin B: = 255; num: = getbytebits (B); {use the function to obtain} showmessage (inttostr (Num); {8} num: = bitarr [B]; {retrieve directly using arrays} showmessage (inttostr (Num); {8} B: = 254; num: = getbytebits (B ); {Get using function} showmessage (inttostr (Num); {7} num: = bitarr [B]; {retrieve using array directly} showmessage (inttostr (Num )); {7} end; end.
That small function, After pondering for half a day, understands (ashamed); it will be okay to judge other numbers in the future, for example, to judge INTEGER:
Function getintbits (X: integer): byte; begin result: = 0; while x 0 do begin if odd (x) Then Inc (result); X: = x SHR 1; end; end;