4 Replies Latest reply: Apr 19, 2008 6:18 AM by 807591 RSS

    Conversion from BitSet to long

    807591
      Hi!

      I want to convert a BitSet to a number in long format, and it shouldn't be very complicated because BitSet uses an internal array of longs, but I don't know how to do it.

      Any idea?

      Thanks!
        • 1. Re: Conversion from BitSet to long
          JosAH
          Note that a long (lower case ell) can only store 64 bits:
          long result= 0L;
          BitSet bs= ...;
          for (int i = bs.nextSetBit(0); i >= 0 && i < 64; i = bs.nextSetBit(i+1))
             result|= 1L<<i;
          kind regards,

          Jos
          • 2. Re: Conversion from BitSet to long
            807591
            Thanks so much!
            I always have a lot of problems with bits! In the reverse mode, that is, from long to BitSet, until now I do:
            long data      = ..
            String sd = Long.toBinaryString(data);
            and then I convert the String to BitSet, is that very few efficient??
            • 3. Re: Conversion from BitSet to long
              JosAH
              platters wrote:
              Thanks so much!
              I always have a lot of problems with bits! In the reverse mode, that is, from long to BitSet, until now I do:
              long data      = ..
              String sd = Long.toBinaryString(data);
              and then I convert the String to BitSet, is that very few efficient??
              If you want only the first 64 bits, why are you using a BitSet anyway? Converting to and from a long all the time isn't very efficient. You can use the long itself as if it were a 64 bit set. A few getBit(long set, int bit) and setBit(long set, int bit, boolean value) methods are al you have to implement:
              boolean getBit(long set, int bit) { // get bit 'bit' from the set
                 return (set&(1L<<bit)) != 0;
              }
              long setBit(long set, int bit, boolean value) { // return the new set with bit 'bit' (un)set
                 if (value)
                    return set|(1L<<bit);
                 else
                    return set&~(1<<bit);
              }
              kind regards,

              Jos
              • 4. Re: Conversion from BitSet to long
                807591
                JosAH wrote:
                If you want only the first 64 bits, why are you using a BitSet anyway? Converting to and from a long all the time isn't very efficient. You can use the long itself as if > it were a 64 bit set. A few getBit(long set, int bit) and setBit(long set, int bit, boolean value) methods are al you have to implement:
                In fact I just need 64 bits as a maximum. I wan to read a given number of bits from a long and that's why I need to convert from long to BitSet.
                Anyway, your answers are so useful, thanks a lot!