0

I saw that we can encode an array of ints into a BitSet and retrieve them as in :

int[] ints = new int[]{5, 7, 25, 100102244};

BitSet b = new BitSet();
for (int i=0;i<ints.length;i++)
    b.set(ints[i]);
b.stream().forEach(i -> System.out.println(i));

which outputs

5
7
25
100102244

Is it possible to do the same for an array of longs ?

Thanks in advance,

user2598997
  • 287
  • 1
  • 2
  • 12
  • Why are you using `BitSet` in this way? The `BitSet` will get unnecessarily big if your numbers are big. Why are you doing this? – Sweeper May 29 '21 at 02:08
  • Hi, the longs in the array are positions in a Random access file, the array length can change so I'm looking to a way to store them in one value of 8 bytes. – user2598997 May 29 '21 at 02:16
  • 1
    Your current code certainly _does not_ store them in 8 bytes. Why do you need it in 8 bytes? I didn't quite understand your explanation. – Sweeper May 29 '21 at 02:19
  • You can use an array (or other collection) of longs if, and only if, each long's _value_ is in the range 0 to Integer.MAX_VALUE. (And there is sufficient memory available for the largest value; e.g. if your largest value is 2 billion, you'll need several hundred megabytes in your JVM. Neardupe https://stackoverflow.com/questions/35677938/ ) – dave_thompson_085 May 29 '21 at 04:19

1 Answers1

0

Use LongBuffer:

import java.nio.*;
import java.util.*;

var buffer = LongBuffer.wrap(new long[] { 5, 7, 25, 100102244 });
var bitset = BitSet.valueOf(buffer);

System.out.println(bitset);

for (long l : bitset.toLongArray()) {
    System.out.println(l);
}
{0, 2, 64, 65, 66, 128, 131, 132, 194, 197, 198, 204, 205, 206, 208, 209, 210, 212, 213, 214, 215, 216, 218}
5
7
25
100102244
Allen D. Ball
  • 1,916
  • 1
  • 9
  • 16