一个字节有 8 个位, 这些位可能是 0 也可能是 1; 现在要算出一个字节中是 1 的位共有多少个.

第一种方法是一个函数;
第二种方法笨了点, 是先把 256 种可能值给一个数组, 随时调取.

第一种方法虽然灵巧, 但不如第二种方法快(作者书中说: 在非特殊情况下, 一般要快到 10 倍左右);
第二种方法虽然快捷, 并且使用方便, 但要以 256 个字节的数组空间为代价.
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{方法1: 获取函数}
function GetByteBits(x: Byte): Byte;
begin
  Result := 0;
  while x <> 0 do
  begin
    if Odd(x) then Inc(Result);
    x := x shr 1;
  end;
end;

{方法2: 把所有可能的值放在一个常数数组}
const
  BitArr: array[0..MAXBYTE] of Byte = (
    0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
    1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
    1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
    2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
    1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
    2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
    2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
    3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8);

{测试}
procedure TForm1.Button1Click(Sender: TObject);
var
  b,num: Byte;
begin
  b := 255;
  num := GetByteBits(b);      {使用函数获取}
  ShowMessage(IntToStr(num)); {8}
  num := BitArr[b];           {直接使用数组获取}
  ShowMessage(IntToStr(num)); {8}

  b := 254;
  num := GetByteBits(b);      {使用函数获取}
  ShowMessage(IntToStr(num)); {7}
  num := BitArr[b];           {直接使用数组获取}
  ShowMessage(IntToStr(num)); {7}
end;

end.

那个小函数, 琢磨了半天才明白(惭愧); 以后判断其他数也没问题了, 譬如判断 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;

posted on 2008-03-17 23:27  万一  阅读(3194)  评论(10编辑  收藏  举报