Конференция ".Net" » Конверацию BitArray в byte[] [C#, Win2k]
 
  • nippo (24.11.05 14:44) [0]
    Извините за делитантский вопрос, вызванный срочной необходимостью перехода на VS C#.
    Как выполнить конверацию BitArray в byte[]
  • Lamer@fools.ua © (24.11.05 20:21) [1]
    >Как выполнить конверацию BitArray в byte[]

    Приблизительно так:
           byte[] BitArrayToByteArray(BitArray input)
           {
               const int BITS_IN_BYTE = 8;

               if (input == null)
               {
                   throw new ArgumentNullException("input");
               }


               byte[] result = new byte[(input.Count + (BITS_IN_BYTE - 1)) / BITS_IN_BYTE];
               int resultIndex = 0;
               byte curByte = 0;
               byte curBitIndex = 0;

               for (int i = 0; i < input.Count; i++)
               {
                   byte bit = input[i] ? (byte)1 : (byte)0;

                   curByte += (byte)(bit << curBitIndex);
                   curBitIndex++;
                   if (curBitIndex % BITS_IN_BYTE == 0)
                   {
                       curBitIndex = 0;
                       result[resultIndex] = curByte;
                       resultIndex++;
                       curByte = 0;
                   }

               }

               if (curBitIndex > 0)
               {
                   result[resultIndex] = curByte;
               }


               return result;
           }

  • ИА (25.11.05 04:32) [2]
    Хм. А вызвать BitArray.CopyTo() не проще будет? :)
  • Lamer@fools.ua © (25.11.05 09:02) [3]
    >>ИА   (25.11.05 04:32) [2]

    >А вызвать BitArray.CopyTo() не проще будет? :)
    Таки да :-)
  • Lamer@fools.ua © (25.11.05 09:05) [4]
    P.S. К тому же и работать, наверное, побыстрее будет.
  • Lamer@fools.ua © (25.11.05 09:11) [5]
    Тогда так:
    byte[] BitArrayToByteArray(BitArray input)
    {
       const int BITS_IN_BYTE = 8;

       if (input == null)
       {
           throw new ArgumentNullException("input");
       }


       byte[] result = new byte[(input.Count + (BITS_IN_BYTE - 1)) / BITS_IN_BYTE];

       input.CopyTo(result, 0);

       return result;
    }

 
Конференция ".Net" » Конверацию BitArray в byte[] [C#, Win2k]
Есть новые Нет новых   [120101   +61][b:0][p:0.002]