Convertir un texte en sa representation binaire et inversement

Contenu du snippet

{ Conversion d'un texte vers sa représentation binaire
}
function StrToStrBin(const S: string): string;
var pOutput : pChar;
    pInput : ^byte;
    N, LenInput : integer;
const
  AtBin : array[boolean] of char = '01';
begin
  LenInput := Length(S);
  SetLength(Result, LenInput shl 3);
  pInput := @S[1];
  pOutput := pChar(result);
  for N := 1 to LenInput do
  begin
    pOutput[0] := AtBin[(pInput^ and $80) = $80];
    pOutput[1] := AtBin[(pInput^ and $40) = $40];
    pOutput[2] := AtBin[(pInput^ and $20) = $20];
    pOutput[3] := AtBin[(pInput^ and $10) = $10];
    pOutput[4] := AtBin[(pInput^ and $08) = $08];
    pOutput[5] := AtBin[(pInput^ and $04) = $04];
    pOutput[6] := AtBin[(pInput^ and $02) = $02];
    pOutput[7] := AtBin[(pInput^ and $01) = $01];
    inc(pOutput,8);
    inc(pInput);
  end;
end;

{ Conversion d'une représentation binaire en texte.
}
function StrBinToStr(const S: string): string;
var pInput : PChar;
    pOutput: ^Byte;
    N, LenInput: integer;
const
  AtBin : array['0'..'1'] of byte = (0,1);
begin
  LenInput := Length(S);
  SetLength(result, LenInput shr 3);
  LenInput := Length(result);
  pInput := PChar(S);
  pOutput := @result[1];
  for N := 1 to LenInput do
  begin
    pOutput^ := 0;
    pOutput^ := byte( (AtBin[pInput[0]] shl 7) or
                      (AtBin[pInput[1]] shl 6) or
                      (AtBin[pInput[2]] shl 5) or
                      (AtBin[pInput[3]] shl 4) or
                      (AtBin[pInput[4]] shl 3) or
                      (AtBin[pInput[5]] shl 2) or
                      (AtBin[pInput[6]] shl 1) or
                       AtBin[pInput[7]]
                  );
    inc(pInput, 8);
    inc(pOutput);
  end;
end; 		

Compatibilité : Delphi 5

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.