For this meditation I would like to discus a technique for storing and transporting multiple boolean datum as a single integer.
The uses for this technique are usually involved with game programming, but it's a generalized technique, so apply it where it makes sense! It's also pretty basic stuff, but I think it's worth taking a few moments to think about.
The concept is simple. Since Perl has no boolean data type you invent one by playing with binary math. An integer is just stored in memory as a byte, or slightly more, depending on the precision and the language it's implemented in.
A single boolean value has two values: 0 or 1
So think about that in terms of binary math. Two values or more, stacked next to each other become a byte:
becomes: 10101010
which equals an integer value of 170.
But let's back up and explain that. Here's a smaller example:
as in:
OK... But how is this 'encoded', and how do we retrieve data from that?
Well, binary math simply shifts the digit every time the base value doubles, so numerically the binary digits equal their value multiplied by the value of the digit place.
So In the above example:11111111 1 2631 84268421 = 255
10101010 = 128*1 64*0 32*1 16*0 8*1 4*0 2*1 1*0 ---------- 128+32+8+2 = 170
Simply divide and mod the value against the series of digit values in decending order: 128,64,32,16,8,2, and 1
What those boolean switches mean is completely up to you, obviously, but this is a quick way to deal with it by attempting to force the compiler to use bits to represent true/false values.
Obviously this is a technique that could be used in many languages and development environments. It's not something that I think jumps out at you unless someone shows it to you and then it's ridiculously simple. That's the way it was for me anyway..
In Java I do this with bitwise operators. It reduces the overhead of objects and makes for more compact memory storage when you have thousands of instances, each holding state.
I can imagine some uses in Perl too, so thus, this meditation....
If you wanted to get sneaky you could use this technique as a pseudo binary encoding system inside XML. But hey, don't let me spoil the fun of discovery... :)
Hey Wait! This isn't a Parachute this is a Backpack!!
In reply to Boolean Encoding in Integers by gregor42
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |