I want to iterate over all bits in fixed array:
var fd = open("/dev/urandom")
const bufLen = 1024 div 8
var buf: array[bufLen, char]
discard fd.readChars(buf, 0, bufLen)
fd.close()
var bitField = cast[array[bufLen div sizeof(set[char]), set[char]]](buf)
for i in 0..1023:
if char(i mod 256) in (bitField[i div 256]):
echo 1
else:
echo 0
Is there a better way to do this?
Have never really used sets in Nim yet. Just tried from memory how iterating may work. OK, without that cast result is what I expected, but not with that cast, so I wonder if such a cast may be valid operation at all. And why is the type conversion not allowed? I think I have to reread the manual.
const
L = 64 - 1
type
S = set[0 .. L]
A = array[2, int32]
var
a: A
s: S
a[1] = 3
s = {}
s.incl(0)
s.incl(1)
s.incl(2)
#s = cast[S](a)
#s = S(a)
for i in 0 .. L:
if s.contains(i):
echo "1"
else:
echo "0"
You can try this:
iterator bits*[T:SomeInteger|char](a: openarray[T]): int =
for i in 0..high(a):
var mask = 1
let e = int(a[i])
for j in 0..sizeof(T)*8-1:
yield int((e and mask) != 0)
mask = mask shl 1
for bit in bits("foo"):
echo bit