简体   繁体   中英

How to decrease the length of an integer Array (with binary data [0,1]) without losing data?

I have an integer array of length 900 that contains only binary data [0,1]. I want to short the length of the array without losing binary data formate(original array values).

Is it possible to short the length of array of 900 into 10 or 20 length in C#???

Bitarray类将为您提供int数组长度的近1/32。

You could actually apply some compression on bits and then store it. if its only 1s and 0s, Run-length encoding may help reduce size drastically in not-worst scenarios.

Run length encoding - Wiki article

Try to use System.Collections.BitArray

Here is the sample code:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Collections.BitArray bits = new System.Collections.BitArray(900);

            // Setting all bits to 0
            bits.SetAll(false);

            // Here Im setting 21st bit in array
            bits[21] = true;
            // etc...

            int[] nativeBits = new int[29];

            // Packing your bits in int array
            bits.CopyTo(nativeBits, 0);

            // This prints 2097152. this is 2^21
            Console.WriteLine("First element is:"+nativeBits[0].ToString());
        }
    }
}

nativeBits array consists of only 29 elements. And now you can convert it in string

In fact, you have a binary integer with 900 digits. There are lots of ways you can hold that "number" depending on the what do you want with it and how fast.

Ask yourself:

  • do I need fast set function ( arr[n] = something )
  • do I need fast retrieval function ( val = arr[n] )
  • do I need iteration of some kind, for example find next n for which arr[n] is 1

and so on.

Then, ask again or modify you original question.

Otherwise, BitArray

EDIT:

Since we found something (a little) I would suggest rolling your own class for that.

Class would have a container such as byte[] and methods to set and unset a item on some position.

Checking common 1s from two arrays would be as simple as &&-ing an array on byte to byte basis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM