例如一个Buf: array [0..255] of byte 的数组,我想将所有字节的第一位拿出来排列成一排,接下来把所有字节的第二位拿出来排列成一排,一直到到第八位,再把这些位组成一个256字节的数组,有谁有好点的思路吗?

解决方案 »

  1.   

    移位之后,0~7bit第一位,8~15 bit第二位这句话可以忽略的..我只想说明一下算法的目的
      

  2.   

    可以把目标数组看成一个32*8的二维数组,每排32个字节,第1排是所有的256字节的第1位组成的,其他的依次类推。
    如果是这样的话,只要遍历原数组,然后把每个字节的各位(0..7)依次和目标数组的8个相应字节进行或(OR)操作即可。
    代码如下(未测试):type
      TUnitArray = array[0..255] of Byte;procedure Transform(const source: TUnitArray; var target: TUnitArray);
    var
      i: Integer;
      j: Integer;
      columns: Integer;
      index: Integer;
    const
      Masks: array[0..7] of Byte = (1, 2, 4, 8, 16, 32, 64, 128);
    begin
      FillChar(target, SizeOf(target), 0);  { Initiazlie target Array }
      columns := SizeOf(source) div 8;
      for i := 0 to High(source) do
      begin
        for j := 0 to 7 do
        begin
          index := columns * j + i mod columns;
          target[index] := target[index] or (source[index] and Masks[j]); 
        end;
      end;
    end;
      

  3.   

    下面是我的程序,好像是可以了,不知道效率能不能再提高一点
      ......
        BitIndex: Byte;
        ByteIndex: Integer;
      begin
        BitIndex:= $07;
        ByteIndex:= 0;         
        for i:= 0 to 7 do                               //大循环逐位递增
          for k:= 0 to sizeof(TmpBuf) - 1 do            //小循环遍历数组
          begin
            Buf[ByteIndex]:= Buf[ByteIndex] or ((TmpBuf[k] and Masks[i]) shl BitIndex); //移位,先放高位
            dec(BitIndex);
            if BitIndex = $FF then                      //读满一个字节,字节数加1
            begin
              inc(ByteIndex);
              BitIndex:= $07;
            end;
          end;
      end;