As a (beginner) exercise, I am trying my hand at implementing something like a class in assembly. For this, I would like to create a BitArray of size N and have the operations of init(size)
, set(idx)
, unset(idx)
, get(idx)
, and print()
.
I am starting with the init()
, and here is what I have thus far:
bit_array_init:
# all this has to do is clear N bits (%rdi) starting at address (%rsi)
mov $-1, %rax # mask of all 1's
mov %dil, %cl
shl %cl, %rax # shift left by the number of bits, filling right-side with 0's
andq %rax, (%rsi) # because the mask is all 1's above the bit count, it doesn't matter
ret # if we 'extend too far' since &1 will have no affect
And it can be called like:
movl $0b110110110110110110, -4(%rbp) # add bogus values to stack to confirm function's ok
# 1. Init the bitArray, b = BitArray(BIT_SIZE, address); allocated locally on the stack
mov $12, %edi # size of the bitarray
lea -4(%rbp), %rsi # where the bitarray starts at
call bit_array_init
It will intentionally only allocate 12-bits instead of something like "2 bytes" and leave everything else as-is (again it's for practice/learning and not actually for real-world stuff).
I have a few questions about this:
- Does the above look like an acceptable way to
init
a bit array? Or are there better ways to do this? - I'm passing in the memory address of something on the stack. is this the way that most
init
functions would work? Or should I be passing in (1) something else; or (2) theinit
will pass back the memory address it allocated to?
You have an initializer but not a constructor.
The difference is that a constructor would allocate the memory, then (perhaps inlined) use the initializer.
If you use a constructor, it would allocate the memory, but how much? Always 64 bits would make it safe from the problems discussed above (writing to memory you don't necessarily own) — but would also take 64 bits to store any vector even if only 12 bits.
Further, if the constructor allocates the 64 bits, there'd be no need to
and
to clear those newly allocated bits, one would simple store a (quad word) zero into it.Various more complicated techniques can be use to create variable length bit vectors of sufficient size as desired by the consuming client, but that would merit a new question and answers.