Skip to content

Instantly share code, notes, and snippets.

@Crinfarr
Last active April 28, 2023 20:48
Show Gist options
  • Save Crinfarr/c7f3687bb41a25569c95abd7c70f6e23 to your computer and use it in GitHub Desktop.
Save Crinfarr/c7f3687bb41a25569c95abd7c70f6e23 to your computer and use it in GitHub Desktop.
Some tools for iterating over the bits of various types
package lnk.helpers;
import haxe.io.Bytes;
import haxe.Exception;
private enum Endianness {
BigEndian;
LittleEndian;
}
class IntBitIterator {
var val:Array<Bool>;
public function new(i:Int, endian:Endianness) {
if (i > 255)
throw new Exception("IntBitIterator only supports 8 bit integers; use ByteByteIterator");
this.val = [];
while (i > 0) {
this.val.push((i & 0x1) == 1);
i = i >> 1;
}
while (this.val.length < 8) {
if (endian == LittleEndian)
this.val = [false].concat(this.val);
if (endian == BigEndian)
this.val = this.val.concat([false]);
}
if (endian == LittleEndian)
val.reverse();
if (endian == BigEndian)
null;
}
public function hasNext() {
return val.length > 0;
}
public function next() {
return val.pop() ? 1 : 0;
}
}
class ByteBitIterator {
var val:Array<Bool>;
public function new(b:Bytes, endian:Endianness) {
this.val = [];
for (idx in 0...b.length) {
if (endian == LittleEndian)
this.val = [for (bit in new IntBitIterator(b.get(idx), endian)) bit == 1].concat(this.val);
if (endian == BigEndian)
this.val = this.val.concat([for (bit in new IntBitIterator(b.get(idx), endian)) bit == 1]);
}
}
public static function fromInt(i:Int, endian:Endianness):ByteBitIterator {
return new ByteBitIterator(Bytes.ofHex(StringTools.hex(i)), endian);
}
public function hasNext() {
return val.length > 0;
}
public function next() {
return val.pop() ? 1 : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment