Calculating the biggest number of consecutive ones in a binary number The following code calculates the biggest number of consecutive ones in a binary representation of a number. For example 6 -> 2 (110), 5 -> 1 (101):

String numberAsBinaryString = Integer.toBinaryString(number);
List&lt;String&gt; listOfConsecutiveOneStrings = Arrays.asList(numberAsBinaryString.split("0"));

System.out.println(listOfConsecutiveOneStrings.stream()
                                                  .max(Comparator.comparing(String::length))
                                                  .map(onesSequence -&gt; onesSequence.length())
                                                  .get());


I wonder if there is a more elegant way of writing this especially since this solution involves quite a few conversions. Any opinions are appreciated.
How about this? (maybe needs some adaption in Java):

int consBits(int x) {
    int consecutiveBits = 0;
    for(;x;consecutiveBits++)
        x &amp;= (x&lt;&lt;1u);

    return consecutiveBits;
}


The idea is to binary &amp; a number with a shifted version of itself. If it is not 0 there is a consecutive sequence of ones. Repeat until the result is 0 and we get the total length of consecutive ones.