Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Object-Pascal / Delphi-Language (https://www.delphipraxis.net/32-object-pascal-delphi-language/)
-   -   Delphi Bits in Bytes unwandeln (https://www.delphipraxis.net/96280-bits-bytes-unwandeln.html)

arbu man 21. Jul 2007 12:14


Bits in Bytes unwandeln
 
Hallo,

irgendwie komme ich grade bei einer eigentlich einfachen Sache nicht weiter :wall: Ich babe einen String in den nur zwei Zeichen Vorkommen die '0' und die '1'. Dieser String besteht Quasi aus Bits, nun will ich diesen String wieder in Bytes verwandeln d.h. aus 01110111 soll wieder ein 'w' werden.

Delphi-Quellcode:
function DecodeBitString(ABits: string): string;
var
  Bits: string;
  MyByte: string;
  i, c: integer;
  B: Byte;
begin
  Result := '';
  Bits := ABits;
  // Auffüllen es nicht mit einen ganzen Byte endet
  i := Length(Bits) mod 8;
  if i <> 0 then begin
    c := 8 - i;
    for i := 0 to c do begin
      Bits := Bits + '0';
    end;
  end;
  //c := Length(Bits) div 8;
  c := 10; // Erste 10 Bytes lesen
  for i := 0 to c do begin
    MyByte := Copy(Bits, 1, 8);
    Delete(Bits, 1, 8);
    B := BitsToByte(MyByte);
    Result := Result + Char(B);
  end;
end;

function BitsToByte(ABit: string): Byte;
const
  n : array[0..7]of byte = (128, 64, 32, 16, 8, 4, 2, 1);
var
  i : integer;
begin
  Result := 0;
  for i := 0 to 7 do begin
    if ABit[i] <> '0' then begin
      Inc(Result, n[i]);
    end;
  end;
end;
Irgentwie komm ich da auf ganz andere Zahlen werte, und verdammt langsam ist das ganze auch noch. Vielleicht hat jemand von euch eine Idee wie es besser geht ?

thx, Björn

DeddyH 21. Jul 2007 12:21

Re: Bits in Bytes unwandeln
 
Versuch es mal so:
Delphi-Quellcode:
function BitsToByte(const ABit: string): Byte;
var i: integer;
    sBit: byte;
begin
  sBit := 1;
  Result := 0;
  for i := Length(ABit) downto 1 do
    begin
      if ABit[i] <> '0' then
        Result := Result or sBit;
      sBit := sBit shl 1;
    end;
end;

arbu man 21. Jul 2007 12:23

Re: Bits in Bytes unwandeln
 
Danke für die schnelle Hilfe es geht jetzt :)

marabu 21. Jul 2007 12:29

Re: Bits in Bytes unwandeln
 
Hallo,

hier noch eine Alternative:

Delphi-Quellcode:
function DualStrToCard(const s: string): Cardinal;
var
  i: Integer;
begin
  Result := 0;
  for i := 1 to Length(s) do
    Result := Result shl 1 + Ord(s[i] = '1');
end;
Grüße vom marabu


Alle Zeitangaben in WEZ +1. Es ist jetzt 03:33 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz