Warning/Note: I guess these functions require some idea of how bits work. If you don't know how they work, don't bother to try to use these functions until you've learned. I'm sure Aen or someone wrote a nifty guide about it somewhere.
So, I have nothing better to do that share my silly little bitClip function. It's nothing awesome, it's actually simple and just allows you to set and get values out of an integer.
The downside is that you can't add negative values. I guess a second version of the bitClip version could support it, taking the left-most bit to account, but I'm not going to bother with that at the moment.
First off we have the bitClip function:
v is the value you forward to the function.
ofs is the offset, ranging from 1 to 32.
length is the length of the binary number you want to collect.
int bitClip(int v, int ofs, int length)
{
v = v << (32 - ofs - length);
if (v < 0) v -= $80000000;
return (v >> (31 - length));
}
And the second function just makes it easier for you to think, it adds a number to the integer.
v is the value we forward to work with.
ofs is the offset in the integer.
num is the number you wish to insert.
int bitAdd(int v, int ofs, int num)
{
return v | (num << (ofs - 1));
}
Used in an example where I will add two values and retrieve them:
int value1 = 9;
int value2 = 7;
int x;
x = bitAdd(x,1,value1); // offset 1 = first bit
x = bitAdd(x,5,value2); // offset 5 = fifth bit
// by now the integer x looks like this in binary:
// 01111001
// now you can take out values with bitClip
// x = bitClip(x,3,5); would grab the part within brackets
// 0[11110]01
// and in that case x would be 30
// but we want to log our two values from that one integer
log("value1 = "+str(bitClip(x,1,4)));
log("value2 = "+str(bitClip(x,5,4)));
// v3.log:
// value1 = 9
// value2 = 7
Storing more than one value in each integer is no magic to many of us, and I remember someone talking about returning two values from a funtion, and well, this is a way to do it as well. Just add the values with bitAdd, and withdraw them with bitClip.