Einzelnen Beitrag anzeigen

Alloc

Registriert seit: 18. Apr 2005
Ort: Griesheim
167 Beiträge
 
Delphi 2006 Professional
 
#4

Re: Hex <--> Binär- / Dualzahl ???

  Alt 1. Apr 2006, 10:35
Hi, hier mal meine eigenen kleinen Routinen für Hex->Long, Byte->Bin, Bin->Byte. Sry wegen der Schreibweise, ist noch älterer Code von mir, wo ich bissl anderen Stil hatte

Hex->Bin: IntToBin(HexToLong(hex));
Bin->Hex: IntToHex(BinToInt(bin),Hex-Stellenanzahl);

Delphi-Quellcode:
FUNCTION HexToLong(hex:String):LongWord;
  FUNCTION NormalizeHexString(VAR hex:String):Boolean;
    VAR
      i:Byte;
    BEGIN
      IF hex[1]='$THEN BEGIN
        FOR i:=1 TO Length(hex)-1 DO BEGIN
          hex[i]:=hex[i+1];
        END;
        SetLength(hex, Length(hex)-1);
      END;
      IF (hex[1]='0') AND (UpCase(hex[2])='X') THEN BEGIN
        FOR i:=1 TO Length(hex)-2 DO BEGIN
          hex[i]:=hex[i+2];
        END;
        SetLength(hex, Length(hex)-2);
      END;
      IF Length(hex)=0 THEN
        Result:=False
      ELSE
        Result:=True;
    END;
  VAR
    i:Byte;
  BEGIN
    IF NormalizeHexString(hex) THEN BEGIN
      hex:=UpperCase(hex);
      Result:=0;
      FOR i:=1 TO Length(hex) DO BEGIN
        Result:=Result SHL 4;
        CASE hex[i] OF
          '0'..'9': Result:=Result+Ord(hex[i])-48;
          'A'..'F': Result:=Result+Ord(hex[i])-55;
        ELSE
          Result:=0;
          Exit;
        END;
      END;
    END ELSE BEGIN
      Result:=0;
    END;
  END;

FUNCTION BinToInt(bin:String):Byte;
  VAR
    Add: Integer;
    i: Byte;
  BEGIN
    Result:=0;
    IF Length(bin)<>8 THEN Exit;
    Add:=1;
    FOR i:=8 DOWNTO 1 DO BEGIN
      IF NOT (bin[i] IN ['0','1']) THEN Exit;
      IF bin[i] = '1THEN Inc(Result,Add);
      Add:=Add SHL 1;
    END;
  END;

FUNCTION IntToBin(value:Byte):String;
  VAR
    i:Byte;
  BEGIN
    SetLength(Result,8);
    FOR i:=7 DOWNTO 0 DO BEGIN
      Result[i+1]:=Char((value AND $01)+48);
      value:=value SHR 1;
    END;
  END;
mfG, Chris
Christian Illy
ONI2.net, basicly every important link about Oni.
  Mit Zitat antworten Zitat