I’ve been playing around with Julia lately and have been enjoying it. I have come from python and as a learning exercise was looking at re-writing some code I had written to do least significant bit embedding.
I’m wondering if my re-write below is the best way to write a more complicated generator or if there are better or more efficient ways to implement one.
Apologies if I’ve just missed something obvious.
Original python code below:
def bit_generator(s): for x in s: a = ord(x) i = 0 while i < 7: yield a & 1 a = a >> 1 # bit shifting embeds character backwards i += 1 # signify end with 14 zeros (double ascii null) for x in xrange(14): yield 0
Julia equivalent (without the nulls at the end). This is where I missed yield as I ended up creating two generators to achieve the same - I could have easily just missed something here, but this is what I came up with.
type OrdGenerator s::String end Base.start(x::OrdGenerator) = 1 Base.done(x::OrdGenerator, state) = length(x.s) == state - 1 Base.next(x::OrdGenerator, state) = Int8(x.s[state]), state + 1 type BitGenerator b::Int8 end Base.start(x::BitGenerator) = 1 Base.done(x::BitGenerator, state) = state > 7 function Base.next(x::BitGenerator, state) a = x.b & 1 x.b = x.b >> 1 a, state + 1 end s = "word? w" println("$s : length = $(length(s))") for (i, x) in enumerate(OrdGenerator(s)) println("$i: $x | $(bin(x))") for (j, bit) in enumerate(BitGenerator(x)) println(" $j: $bit") end end
Any comments or advice would be appreciated.