tags:

views:

264

answers:

3
+1  Q: 

Parity bit

Is there a elagant way with delphi (6) to remove the parity bit in a file. In this case every 9e bit.

Cheers Ernest

+4  A: 

Assuming your file is a long bit stream containing 9-bit blocks and you want to output the same stream but with 8-bit blocks (i.e. dropping every 9th bit).

You could read 9 bytes at a time (72 bits = eight 9-bit blocks) and then use bit shifting to put these into eight 8-bit blocks.

You would need some special processing to handle a file that isn't a multiple of 9 bytes, so this is just a rough guide.

procedure TForm1.Button1Click(Sender: TObject);
var
  FSIn: TFileStream;
  FSOut: TFileStream;
  InBuffer: array[0..8] of Byte;
  OutBuffer: array[0..7] of Byte;
  X: Integer;
  BytesRead: Integer;
  BytesToWrite: Integer;
begin
  FSIn := TFileStream.Create('Input.dat', fmOpenRead);
  FSOut := TFileStream.Create('Output.dat', fmCreate);
  try
    for X := 1 to FSIn.Size div 9 do
    begin
      FillChar(InBuffer[0], 9, 0);
      BytesRead := FSIn.Read(InBuffer[0], 9);
      OutBuffer[0] := InBuffer[0];
      OutBuffer[1] := (InBuffer[1] and 127) shl 1 + (InBuffer[2] and 128) shr 7;
      OutBuffer[2] := (InBuffer[2] and 63) shl 2 + (InBuffer[3] and 192) shr 6;
      OutBuffer[3] := (InBuffer[3] and 31) shl 3 + (InBuffer[4] and 224) shr 5;
      OutBuffer[4] := (InBuffer[4] and 15) shl 4 + (InBuffer[5] and 240) shr 4;
      OutBuffer[5] := (InBuffer[5] and 7) shl 5 + (InBuffer[6] and 248) shr 3;
      OutBuffer[6] := (InBuffer[6] and 3) shl 6 + (InBuffer[7] and 252) shr 2;
      OutBuffer[7] := (InBuffer[7] and 1) shl 7 + (InBuffer[8] and 254) shr 1;

      if BytesRead < 9 then
      begin
        // To do - handle case where 9 bytes could not be read from input
        BytesToWrite := 8;
      end else
        BytesToWrite := 8;

      FSOut.Write(OutBuffer[0], BytesToWrite);
    end;
  finally
    FSIn.Free;
    FSOut.Free;
  end;
end;
Bing
+1 it can be done more efficient (pointers, asm and the like), but this is pretty ok for not extreme cases.
Marco van de Voort
Looks like the InBuffer needs to be cleared before each read to handle the case where 9 bytes were not available to be read.
skamradt
A: 

Assuming you can read the thing one on one into an integer.

i := i xor 512;

Tom
But this doesn't eliminate the parity bit.
skamradt
A: 

Thank guys for all your help so far.

The idea is to remove and NOT to clear a 9th bit. Sorry for the confusion.