在 Java 中,您可以创建一个大小为 8 的 BitSet 并将其存储为一个字节以便输出吗?BitSets 的文档没有提到它。这是否意味着没有?
4 回答
5
你不能投射BitSet
到byte
.
你可以编写代码来做你想做的事。给定一个BitSet
命名的bits
,你去:
byte output = 0;
for (int i = 0; i < 8; i++) {
if (bits.get(i)) {
output |= 1 << (7 - i);
}
}
更新:上面的代码假设您的位从左到右索引为 0 到 7。例如,假设01101001
您认为位 0 的位是最左边的 0。但是,如果您从右到左分配位,则位 0 将是最右边的 1。在这种情况下,您需要output |= 1 << i
。
于 2011-04-18T18:05:30.523 回答
2
没有什么内置的。显然,您可以自己实现。
于 2011-04-18T18:00:03.793 回答
0
位集是位数组
JVM 使用 32 位堆栈单元,即 JVM 中的每个寄存器存储一个 32 位地址
我们知道原始布尔值设置为 1 位,但处理为 32 位。布尔数组将被视为字节数组
在 BitSet 中,位集的每个组件都有一个布尔值
每个位集都有一个当前大小,即该位集当前使用的空间位数。请注意,大小与位集的实现有关,因此它可能会随着实现而改变。位集的长度与位集的逻辑长度相关,并且独立于实现来定义。
于 2011-04-18T18:09:49.307 回答
-1
BitSet 类显然不打算将其位导出或导入到本机数据类型,如果您只想处理单个字节的固定大小,那么它也相当繁重。因此,如果您只想独立操作字节的位然后使用生成的字节,它可能不是您所需要的。看来您可能只想使用这样的 API:
SimpleBitSet bs = new SimpleBitSet( 'A' );
bs.setBit( 5 );
byte mybyte = bs.getByte();
因此,这样一个简化的位集的实现可能如下所示:
public class SimpleBitSet
{
private byte bits;
public SimpleBitSet( int bits )
{
this.bits = (byte) bits;
}
public byte getByte()
{
return bits;
}
public boolean getBit( int idx )
{
checkIndex( idx );
return ( bits & ( 1 << idx ) ) != 0;
}
public void setBit( int idx )
{
checkIndex( idx );
bits |= 1 << idx;
}
public void clearBit( int idx )
{
checkIndex( idx );
bits &= ~( 1 << idx );
}
protected void checkIndex( int idx )
{
if( idx < 0 || idx > 7 )
throw new IllegalArgumentException( "index: " + idx );
}
}
于 2011-04-18T19:06:46.617 回答