Delphi algorithm and Data Structure Learning and perception [3]: getting the number of non-vacant bytes

Source: Internet
Author: User
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;

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.