Java 迭代字节数组中的位 [英] Java Iterate Bits in Byte Array

查看:30
本文介绍了Java 迭代字节数组中的位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何迭代字节数组中的位?

How can i iterate bits in a byte array?

推荐答案

您必须编写自己的 Iterable 实现,它接受一个字节数组,然后创建 Iterator 值,它记住了字节数组中的当前索引当前字节中的当前索引.那么这样的实用方法就会派上用场:

You'd have to write your own implementation of Iterable<Boolean> which took an array of bytes, and then created Iterator<Boolean> values which remembered the current index into the byte array and the current index within the current byte. Then a utility method like this would come in handy:

private static Boolean isBitSet(byte b, int bit)
{
    return (b & (1 << bit)) != 0;
}

(其中 bit 的范围从 0 到 7).每次调用 next() 时,您都必须增加当前字节中的位索引,如果到达第 9 位",则增加字节数组中的字节索引.

(where bit ranges from 0 to 7). Each time next() was called you'd have to increment your bit index within the current byte, and increment the byte index within byte array if you reached "the 9th bit".

这不是真的 - 但有点痛苦.如果您想要一个示例实现,请告诉我...

It's not really hard - but a bit of a pain. Let me know if you'd like a sample implementation...

这篇关于Java 迭代字节数组中的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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