Sometimes I need to look up an object in an array by matching several of its properties. The values might be anything, but let’s say for example I need to match a boolean, and two numbers, where I know the values will be within some limit, say one is always between 0-15, and the other is a 32-bit int.
In the past I’ve used strings to put together values into something easy to read, like “false,7,234576” and stored them in an array, then build the search string the same way from the values I want to find, and use IndexOf on the string array to look up the index, then I can get the object from that index.
That works, but it’s clumsy. Because it involves string conversion and parsing, it’s ridiculously slow.
So I took a clue from the hardware world (where memory is scarce), and got the idea to treat a 64-bit integer as a memoryblock and pack it with bits, then use IndexOf on that instead. It isn’t quite as easy to build the search value, but it works faster and saves memory.
I was just wondering if anyone else does this.
// Storing multiple values in an Integer
' ( or Using Integers as Memoryblocks )
' value A: 0-1 = 1 bit
' value B: 0-15 = 4 bits
' value C: 0-4294967296 = 32 bits
// 1+4+32 = 37 bits, so in a 64-bit integer we'll have 27 empty bits
// Example: this should give a result of 1's
dim A, B, C, D as Integer
A = 1
B = 15
C = 1023
' pack the values into D
D = A + Bitwise.ShiftLeft( B, 1 ) + Bitwise.ShiftLeft( C, 5 )
' check it
dim iA, iB, iC as integer
dim sA, sB, sC, sD, e as string
e = EndOfLine
iA = Bitwise.BitAnd( D, 1 )
iB = Bitwise.BitAnd( D, 30 ) \ 2
iC = Bitwise.ShiftRight( D, 5 )
sA = str( iA )
sB = str( iB )
sC = str( iC )
sD = D.ToBinary()
msgbox "Encoded values:"+e+sD+e+sA+e+sB+e+sC