【问题标题】:How to create x-bit binary number with number of leftmost bits set如何创建设置了最左边位数的 x 位二进制数
【发布时间】:2016-01-11 19:09:46
【问题描述】:

我想创建一个x位二进制数并指定最左边的位数。

即创建一个 8 位数字,其中 6 个最左边的位全部设置为 1111 1100

类似地创建 16 位数字,其中 8 位全部设置为 1111 1111 0000 0000

需要能够为大数字(128 位)执行此操作。有没有使用核心库的现有方法?

谢谢

【问题讨论】:

  • 您希望如何表示您的 128 位数字?一个 BitSet 就足够了,还是你想要一个 BigInteger?您需要支持任何宽度的数字(例如,127 位?),还是只支持 2 的幂(例如 8、16、32、64、128)?

标签: java binary bits


【解决方案1】:

考虑使用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;
}

Here are some unit tests

然后,您可以使用 BitSet 的公共 API(此处显示 Java 8):

BitSet 就是为此而设计的(精确的位操作),它还为您提供了任意长度(不将您限制为 64 位,例如 long 会)。

【讨论】:

  • 我需要支持 128 但数字但我需要能够任意指定左位数。即创建一个 128 位数字,最左边的 122 位设置为 1。加上我使用 java 7
【解决方案2】:

您可以使用两个循环。一个代表所有的 1,另一个代表所有的 0。

或者使用 Java 8 也可以

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

【讨论】:

  • 这并没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
  • @skypjack 虽然没有提供完整的答案,但它确实说明了 OP 应该做什么。这只是两行代码。如果不为他们做功课,你还能给出多少解释?
  • 我在 3 小时前发表评论,您在 50 分钟前编辑了问题,然后您发表评论询问出了什么问题。你是认真的吗?这不是一个完整的答案,现在它有更多细节,也许可以。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-02-11
  • 2012-03-13
  • 2011-05-05
  • 2019-03-31
  • 2018-09-15
  • 2021-07-11
  • 1970-01-01
  • 2012-05-21
相关资源
最近更新 更多