bitClip and bitAdd
Displaying 1-2 of 2 total.
1
Please enter a numerical value for the importance of this sticky.
Enter 0 to unsticky.
zaril

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.

Posted on 2004-08-04 23:42:15

zaril

sidenote: i used these functions one or two years ago in one of my projects, the bitClip function is probably able to be simplified by some simple bit-operation, but i'm too tired right now to think about it. use this code, modify it, praise it or throw it away. it's here, deal with it.

Posted on 2004-08-04 23:48:34


Displaying 1-2 of 2 total.
1
 
Newest messages

Ben McGraw's lovingly crafted this website from scratch for years.
It's a lot prettier this go around because of Jon Wofford.
Verge-rpg.com is a member of the lunarnet irc network, and would like to take this opportunity to remind you that regardless how babies taste, it is wrong to eat them.