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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
No comments:
Post a Comment