比特集,并从整数/长 [英] BitSet to and from integer/long

查看:153
本文介绍了比特集,并从整数/长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有,我想上执行位操作整数,我怎么可以加载它变成一个java.util.BitSet中?我怎样才能将其转换回int或长时间?我不那么在意BitSet的大小 - 它永远是长32或64位。我只是想使用set(),清(),nextSetBit()和nextClearBit()方法,而不是位运算符,但我无法找到一个简单的方法来初始化位以数字类型设置。

If I have an integer that I'd like to perform bit manipulation on, how can I load it into a java.util.BitSet? How can I convert it back to an int or long? I'm not so concerned about the size of the BitSet -- it will always be 32 or 64 bits long. I'd just like to use the set(), clear(), nextSetBit(), and nextClearBit() methods rather than bitwise operators, but I can't find an easy way to initialize a bit set with a numeric type.

推荐答案

以下code创建一个位从长期的价值和副反之亦然设置:

The following code creates a bit set from a long value and vice versa:

public class Bits {

  public static BitSet convert(long value) {
    BitSet bits = new BitSet();
    int index = 0;
    while (value != 0L) {
      if (value % 2L != 0) {
        bits.set(index);
      }
      ++index;
      value = value >>> 1;
    }
    return bits;
  }

  public static long convert(BitSet bits) {
    long value = 0L;
    for (int i = 0; i < bits.length(); ++i) {
      value += bits.get(i) ? (1L << i) : 0L;
    }
    return value;
  }
}

编辑:现在两个方向,@leftbrain:事业,你是对的。

EDITED: Now both directions, @leftbrain: of cause, you are right

这篇关于比特集,并从整数/长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆