1

I currently have 16 bits I want to set to variables (2 separate bytes). I've used the BitSet object to hold my bits and while in Java 1.7 there is a toByteArray() method, I need something that works on earlier versions of Java. It doesn't need to use BitSet, but I would prefer that it does (if possible).

If someone could tell me how to write something like 01101011 to a byte, I think that would help me enough. Thanks!

4

1 回答 1

1

您可以使用这段代码来做到这一点:

public static byte convert(BitSet bits, int offset) {
  byte value = 0;
  for (int i = offset; (i < bits.length() && ((i + offset) < 8)) ; ++i) {
    value += bits.get(i) ? (1 << i) : 0;
  }
  return value;
}

因此,要转换两个字节,您将执行以下操作:

BitSet b = ....;
byte b1 = Helper.convert(b, 0);
byte b2 = Helper.convert(b, 8);
于 2012-08-26T00:11:10.020 回答