Sunday, June 16, 2013

Biterator

Just needed to write some bit encoding code and needed a bit stream from a byte array. Looked around a bit, couldn't find something quick so wrote it.

class Biterator(ba: Array[Byte]) extends Iterator[Int]{
var bitIndex = 0
var byteIndex = 0
override def hasNext() =
byteIndex < ba.size - 1 ||
byteIndex == ba.size - 1 && bitIndex < 7
def next(): Int = {
val bit = getNthBit(ba(byteIndex), bitIndex)
bitIndex += 1
if(bitIndex == 8){
byteIndex += 1
bitIndex = 0
}
bit
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment