Arbeiten mit Bits |
|
| System | Win9x, WinNT, Win2000, WinXP, Vista, Win7 |
|---|---|
| Ab Delphi-Version | Delphi 1 |
| Letzte Änderung | 28.09.2010 |
Die Arbeit mit Bits (1011000101) kann sehr nützlich sein, vor allem für Verschlüsselung. Ich habe ein paar Routinen zur Umwandlung eines Zeichens in einen String (Länge 8) aus '1' und '0' und umgekehrt geschrieben.
const
B1: Byte = 128;
B2: Byte = 64;
B3: Byte = 32;
B4: Byte = 16;
B5: Byte = 8;
B6: Byte = 4;
B7: Byte = 2;
B8: Byte = 1;
// wird von den Routinen benögtigt
function TestBit(ByteToTest, BitNr: Byte): Boolean;
var
I: Integer;
begin
Result := False;
if BitNr <= 8 then
begin
I := ByteToTest shl BitNr;
Result := ((128 and I) = 128);
end;
end;
{Diese Funktion wandelt ein Zeichen in die zugehörige Bit-Folge}
function CharToBit(C: Char): string;
var
A: Byte;
B: Byte;
begin
Result := '';
B := Byte(C);
for A := 0 to 7 do
if TestBit(B, A) then
Result := Result + '1'
else
Result := Result + '0';
end;
// String (Länge 8, aus '1' und '0') -> Char
function BitToChar(S: string): Char;
var A, B: byte;
T: string;
begin
Result := ' ';
T := S;
if length(T) < 8 then
while length(T) <> 8 do
T := T + '0';
if length(T) > 8 then
delete(T, 9, length(T));
B := 0;
for A := 1 to 8 do
if T[A] = '1' then
case A of
1: B := B or B1;
2: B := B or B2;
3: B := B or B3;
4: B := B or B4;
5: B := B or B5;
6: B := B or B6;
7: B := B or B7;
8: B := B or B8;
end;
Result := Char(B);
end;
// Byte in String / String in Byte
function ByteToBit(B: Byte): string;
begin
Result := CharToBit(Char(B));
end;
function BitToByte(S: string): Byte;
begin
Result := Byte(BitToChar(S));
end;
B1: Byte = 128;
B2: Byte = 64;
B3: Byte = 32;
B4: Byte = 16;
B5: Byte = 8;
B6: Byte = 4;
B7: Byte = 2;
B8: Byte = 1;
// wird von den Routinen benögtigt
function TestBit(ByteToTest, BitNr: Byte): Boolean;
var
I: Integer;
begin
Result := False;
if BitNr <= 8 then
begin
I := ByteToTest shl BitNr;
Result := ((128 and I) = 128);
end;
end;
{Diese Funktion wandelt ein Zeichen in die zugehörige Bit-Folge}
function CharToBit(C: Char): string;
var
A: Byte;
B: Byte;
begin
Result := '';
B := Byte(C);
for A := 0 to 7 do
if TestBit(B, A) then
Result := Result + '1'
else
Result := Result + '0';
end;
// String (Länge 8, aus '1' und '0') -> Char
function BitToChar(S: string): Char;
var A, B: byte;
T: string;
begin
Result := ' ';
T := S;
if length(T) < 8 then
while length(T) <> 8 do
T := T + '0';
if length(T) > 8 then
delete(T, 9, length(T));
B := 0;
for A := 1 to 8 do
if T[A] = '1' then
case A of
1: B := B or B1;
2: B := B or B2;
3: B := B or B3;
4: B := B or B4;
5: B := B or B5;
6: B := B or B6;
7: B := B or B7;
8: B := B or B8;
end;
Result := Char(B);
end;
// Byte in String / String in Byte
function ByteToBit(B: Byte): string;
begin
Result := CharToBit(Char(B));
end;
function BitToByte(S: string): Byte;
begin
Result := Byte(BitToChar(S));
end;