如何创建具有最左边位数集的 x 位二进制数
How to create x-bit binary number with number of leftmost bits set
我想创建一个x位二进制数,并指定最左边的位数集。
即创建一个 8 位数字,最左边的 6 位全部设置为 1111 1100
类似地创建 16 位 - 左 8 位的数字全部设置为 1111 1111 0000 0000
需要能够对大数字(128 位)执行此操作。是否有使用核心库执行此操作的现有方法?
谢谢
您可以使用两个循环。一个代表所有 1,另一个代表所有 0。
或者使用 Java 8 你可以做到
InStream.range(0, ones).forEach(i -> System.out.print(1));
InStream.range(ones, bits).forEach(i -> System.out.print(0));
考虑使用 BitSet
,像这样:
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;
}
然后,您可以使用 BitSet
使用其 public API(此处显示 Java 8):
BitSet
专为此设计(精确位操作),它也为您提供任意长度(不限制您使用 64 位,例如 long
会) .
我想创建一个x位二进制数,并指定最左边的位数集。
即创建一个 8 位数字,最左边的 6 位全部设置为 1111 1100
类似地创建 16 位 - 左 8 位的数字全部设置为 1111 1111 0000 0000
需要能够对大数字(128 位)执行此操作。是否有使用核心库执行此操作的现有方法?
谢谢
您可以使用两个循环。一个代表所有 1,另一个代表所有 0。
或者使用 Java 8 你可以做到
InStream.range(0, ones).forEach(i -> System.out.print(1));
InStream.range(ones, bits).forEach(i -> System.out.print(0));
考虑使用 BitSet
,像这样:
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;
}
然后,您可以使用 BitSet
使用其 public API(此处显示 Java 8):
BitSet
专为此设计(精确位操作),它也为您提供任意长度(不限制您使用 64 位,例如 long
会) .