user805703
user805703

Reputation: 247

How to create x-bit binary number with number of leftmost bits set

I would like to create to create an x-bit binary number and specify the number of leftmost bits set.

I.e To create a 8-bit number with 6 most left bits all set as in 1111 1100

Similarly to create 16 bit - number with the 8 left bits all set resulting in 1111 1111 0000 0000

Need to be able to do this for large numbers (128 bits). Is there an existing way to do this using the core libs?

Thanks

Upvotes: 3

Views: 583

Answers (2)

randers
randers

Reputation: 5146

Consider using a BitSet, like this:

import java.util.BitSet;

/**
 * Creates a new BitSet of the specified length
 * with the {@code len} leftmost bits set to {@code true}.
 *
 * @param totalBits The length of the resulting {@link BitSet}.
 * @param len       The amount of leftmost bits to set.
 * @throws IllegalArgumentException If {@code len > totalBits} or if any of the arguments is negative
 */
public static BitSet leftmostBits(int totalBits, int len)
{
    if (len > totalBits)
        throw new IllegalArgumentException("len must be smaller or equal to totalBits");
    if (len < 0 || totalBits < 0)
        throw new IllegalArgumentException("len and totalBits must both be positive");
    BitSet bitSet = new BitSet(totalBits);
    bitSet.set(0, len);
    return bitSet;
}

Here are some unit tests

Then, you can use that BitSet using its public API (here Java 8 is shown):

BitSet public API as of Java 8

BitSet has been designed for this (precise bit manipulation), and it provides you with an arbitrary length as well (does not limit you to 64 bits, like long for example would).

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

You can use two loops. One for all the 1's and another for all the 0's.

Or using Java 8 you can do

InStream.range(0, ones).forEach(i -> System.out.print(1));
InStream.range(ones, bits).forEach(i -> System.out.print(0));

Upvotes: 0

Related Questions