随笔 - 2146  文章 - 97 评论 - 11767 trackbacks - 253


unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    Button5: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
    procedure Button5Click(Sender: TObject);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

type {下面两个结构体的大小都是 4 字节, 相当于一个 Cardinal 或 Integer 或 DWORD 的大小}
  TMyByteStruct = record
    b1: Byte;
    b2: Byte;
    b3: Byte;
    b4: Byte;
  end;

  TMyWordStruct = record
    w1: Word;
    w2: Word;
  end;

procedure TForm1.Button1Click(Sender: TObject);
var
  ByteStruct: TMyByteStruct;
  num: Cardinal;
begin
  {假如}
  ByteStruct.b1 := $A1;
  ByteStruct.b2 := $B2;
  ByteStruct.b3 := $C3;
  ByteStruct.b4 := $D4;
  {那么}
  num := Cardinal(ByteStruct);
  ShowMessageFmt('$%x', [num]); //$D4C3B2A1
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  WordStruct: TMyWordStruct;
  num: Cardinal;
begin
  {假如}
  WordStruct.w1 := $ABCD;
  WordStruct.w2 := $1234;
  {那么}
  num := Cardinal(WordStruct);
  ShowMessageFmt('$%x', [num]); //$1234ABCD
end;

procedure TForm1.Button3Click(Sender: TObject);
var
  num: Cardinal;
  ByteStruct: TMyByteStruct;
begin
  num := $ABCD1234;
  Cardinal(ByteStruct) := num;
  //ByteStruct := TMyByteStruct(num); {这同上一句}

  ShowMessageFmt('$%x', [ByteStruct.b1]); //$34
  ShowMessageFmt('$%x', [ByteStruct.b2]); //$12
  ShowMessageFmt('$%x', [ByteStruct.b3]); //$CD
  ShowMessageFmt('$%x', [ByteStruct.b4]); //$AB
end;

procedure TForm1.Button4Click(Sender: TObject);
var
  num: Cardinal;
  WordStruct: TMyWordStruct;
begin
  num := $ABCD1234;
  Cardinal(WordStruct) := num;
  //WordStruct := TMyWordStruct(num); {这同上一句}

  ShowMessageFmt('$%x', [WordStruct.w1]); //$1234
  ShowMessageFmt('$%x', [WordStruct.w2]); //$ABCD
end;

procedure TForm1.Button5Click(Sender: TObject);
var
  ByteStruct: TMyByteStruct;
  WordStruct: TMyWordStruct;
begin
  WordStruct.w1 := $2211;
  WordStruct.w2 := $4433;

  Cardinal(ByteStruct) := Cardinal(WordStruct);
  //ByteStruct := TMyByteStruct(WordStruct); {这同上一句}

  ShowMessageFmt('$%x', [ByteStruct.b1]); //$11
  ShowMessageFmt('$%x', [ByteStruct.b2]); //$22
  ShowMessageFmt('$%x', [ByteStruct.b3]); //$33
  ShowMessageFmt('$%x', [ByteStruct.b4]); //$44
end;

end.

posted on 2009-01-10 19:48  万一  阅读(...)  评论(...编辑  收藏