LongStream


Java: Breakdown a long number to the powers of two it is composed from 1

The following function will accept a long number as input and will produce an LongStream, which is a sequence of primitive long-valued elements that supports sequential and parallel aggregate operations.

public static LongStream splitToPowersOfTwo(final long input) {

    long temp = input;
    final LongStream.Builder builder = LongStream.builder();

    while (temp != 0) {

        //Long.lowestOneBit: Finds the lowest-order ("rightmost") one-bit in the specified long value and returns a long number that has only the bit in the previously matched position set as 1. This value is a power of two that is one of the components of the number. If the number is zero, the function returns zero.
        final long powerOfTwo = Long.lowestOneBit(temp);
        builder.add(powerOfTwo);
        //We update our temp by subtracting the number we got, our goal is to remove the previously matched bit and get the next one on the next iteration.
        temp = temp & ~ powerOfTwo;
    }

    return builder.build();
}

We used Long.lowestOneBit as it makes it easy for us to breakdown the number to its power of two components by matching for us only one bit at time.

Example of usage:

Scenario: We want to breakdown a long number to the powers of two that their sum produces the number and create a String with those values. Using our function, we can do the following:

final String output = splitToPowersOfTwo(flags).mapToObj(Long::toString).collect(Collectors.joining(", "));

Note: an LongStream is not the same as a Stream<Long>, we used .mapToObj(Long::toString) which calls the static method Long.toString(long). This is different to calling .map(Long::toString) on a Stream<Long> as the latter won’t compile because it is ambiguous.