unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Edit1: TEdit;
    StaticText1: TStaticText; //这组件跟标签label效果差不多
    StaticText2: TStaticText;
    Edit2: TEdit;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    function BitToInt(str:string):Integer; //2进制转10进制函数声明
    function IntToBit(i:Integer):string; //10进制转2进制函数声明
    procedure Button2Click(Sender: TObject);
  private

    { Private declarations }
  public

    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
function tform1.BitToInt(str:string):Integer;  //2进制转10进制
var
  i,size:Integer;
begin
  Result:=0;
  size:=Length(str);
  for i:=size downto 1 do
  begin
    if Copy(str,i,1)='1' then
    Result:=Result+(1 shl (size-i));
  end;
end;
function tform1.IntToBit(i: integer): string;  //10进制转2进制
begin
 while i <>0 do
 begin
   result:=Format('%d'+result,[i mod 2]); //i mod 2取余,再用format让这个字符在字符串中排在最前面
   i:=i div 2  //上面的取余并不影响到i的值,这里还要div一次,得出商用于下一次循环
 end
end;
procedure TForm1.Button1Click(Sender: TObject);  //调用BitToInt
begin
Edit2.Text:=IntToStr(BitToInt(Edit1.Text));
end;

procedure TForm1.Button2Click(Sender: TObject);  //调用IntToBit
var
  i:Integer;
begin
  i:=StrToInt(Edit2.Text);
  Edit1.Text:=IntToBit(i);
end;
end.

可能有人对COPY函数不太了解,下面给出原型以供参考:

function Copy(
  S: String;      {字符串或动态数组}
  Index: Integer; {起始位置}
  Count: Integer  {Copy 个数}
): String;        {如果参数 S 是动态数组, 这里也应该返回动态数组}

可能有人对进制间转换的原理不太明白,或许这个对你有帮助http://www.cnblogs.com/keycode/archive/2010/10/26/1861265.html

posted on 2010-10-26 17:18  巅枫  阅读(1294)  评论(1编辑  收藏  举报