Einzelnen Beitrag anzeigen

Ohwie

Registriert seit: 30. Okt 2006
2 Beiträge
 
Delphi 2006 Professional
 
#1

Bitfelder in Delphi fast wie in C

  Alt 30. Okt 2006, 22:22
Bitfelder zum einfachen Zugriff auf Teile eines Integers werden in C sehr einfach z.B. mit:

typedef struct _XY
{
WORD BF1:2;
WORD BF2:1;
WORD BF3:3;
WORD BF4:1;
WORD BF5:1;
WORD BFRest:8;
} XY;
beschreiben.

In Delphi fehlt diese Möglichkeit leider:
Eine Annäherung geht mit folgender Klassendefinition:

Delphi-Quellcode:
TIFIELD = class
  private
    procedure SetFeld(Start: SmallInt; Breite: SmallInt; BitValue: DWORD);
    function GetFeld(Start: SmallInt; Breite: SmallInt): DWORD;
  public
    property Feld[Start, Breite: SmallInt]: DWORD read GetFeld write SetFeld;
    default;
  end;
  PIFIELD = ^TIFIELD

procedure TIFIELD.SetFeld(Start: SmallInt; Breite: SmallInt; BitValue: DWORD);
var
  Maske: DWORD;
begin
  asm
     mov Edx,Eax
     mov EAx,-1
     mov cx,32
     sub cx,Breite
     shr Eax,cl
     mov cx,Start
     shl Eax,cl
     not EAX
     mov Maske,eax
     mov Eax,BitValue
     shl Eax,cl
     mov BitValue,eax
     mov Eax,[edx]
     and eax,maske
     Or eax,BitValue
     mov [edx],eax
  end;
end;

function TIFIELD.GetFeld(Start, Breite: SmallInt): DWORD;
var
  Maske: DWORD;
begin
  asm
     mov Edx,Eax
     mov EAx,-1
     mov cx,32
     sub cx,Breite
     shr Eax,cl
     mov cx,Start
     shl Eax,cl
     mov Maske,eax

     mov eax,[edx]
     and eax,maske

     mov cx,Start
     shr eax,cl
     mov Result,eax
  end;
  // Result := (Value and Maske) shr Start;
end;
Der Zugriff auf einzelen Bitfelder sieht dann wie folgt aus:

Delphi-Quellcode:
var
   Value:Integer;
   BF:TIFIELD;
   XY:Integer;(oder WORD oder DWORD oder BYTE)

    
   BF := TIFIELD(@XY)
   Value := BF[3,3]; //Zugriff auf 3 Bit's beginnend an der 3. Position
oder:
   BF[5,3]:= 6; //setzt ein Feld von 3 Bit's beginnend an der 5. Position
Ich hoffe es nützt.
  Mit Zitat antworten Zitat