I want to create a matrix representation for a graph algorithm using the least memory possible.
So I decided to try using a bit representation of the values of the matrix, but I also know that doing this by C is (AFAIK) impossible, because a bit is not addressable.
Then I read a post here suggesting to use a struct that can help me do so by using, e.g., an int (4 bytes, so 32-bit) and, with some magic and bitshifts, use it as an “array” of bits.
Got that, but I can’t really realize how exactly I could do this. I got confused…
I’m thinking about using a structure to store a int/void pointer to n bytes corresponding to the least number of bytes to the ‘n’ number of bits allocated and the ‘k’ number of bits in that representation, something such as that.
So I thought you could help me realize what’s the best approach for this kind of solution.
Note: Why I’m so confused? I’m still graduating in Computer Science and I just started to study graphs. Also just finished a laboratory project on that (implemented it as a matrix but used some mathemagic to alloc only half of the matrix and represented it as symectrical), but I’m trying to extend the matter. Also because I got extremely curious 🙂
Thanks all.
P.S.: almost forgot, I’m programming this in C, but I can understand C++, .Net languages and Java very well. Thanks again.
There are a couple of tricky bits here: working on individual bits within a large array; and simulating a 2-dimensional array with a 1-dimensional one. It’s best to solve these separately at first.
Start with some helper functions that let you work on individual bits. Something like:
You then move up a level with a structure to hold the array of bytes, and some data about the dimensions. A 2-dimensional array can be simulated with a 1-d one, by translating a an operation on bit
(x,y)to one on bity*width+x.