Occasionally, it is useful to be able to access individual binary digits of a number in order to read or change them. As an example of this we might mention the initialization of a CLINT object as a power of 2, which can be accomplished easily by setting a single bit.
In the following we shall develop three functions, setbit_l(), testbit_l(), and clearbit_l(), which set an individual bit, test a particular bit, and delete a single bit. The functions setbit_l() and clearbit_l() each return the state of the specified bit before the operation. The bit positions are counted from 0, and thus the specified positions can be understood as logarithms of powers of two: If n_l is equal to 0, then setbit_l(n_l, 0) returns the value 0, and afterwards, n_l has the value 20 = 1; after a call to setbit_l(n_l, 512), n_l has the value 2512 + 1.
int
setbit_l (CLINT a_l, unsigned int pos)
{
int res = 0;
unsigned int i;
USHORT shorts = (USHORT)(pos >> LDBITPERDGT);
USHORT bitpos = (USHORT)(pos & (BITPERDGT - 1));
USHORT m = 1U << bitpos;
if (pos > CLINTMAXBIT)
{
return E_CLINT_OFL;
}
if (shorts >= DIGITS_L (a_l))
{
for (i = DIGITS_L (a_l) + 1; i <= shorts + 1; i++)
{
a_l[i] = 0;
}
SETDIGITS_L (a_l, shorts + 1);
}
if (a_l[shorts + 1] & m)
{
res = 1;
}
a_l[shorts + 1] |= m;
return res;
}
int
testbit_l (CLINT a_l, unsigned int pos)
{
int res = 0;
USHORT shorts = (USHORT)(pos >> LDBITPERDGT);
USHORT bitpos = (USHORT)(pos & (BITPERDGT - 1));
if (shorts < DIGITS_L (a_l))
{
if (a_l[shorts + 1] & (USHORT)(1U << bitpos))
res = 1;
}
return res;
}
int
clearbit_l (CLINT a_l, unsigned int pos)
{
int res = 0;
USHORT shorts = (USHORT)(pos >> LDBITPERDGT);
USHORT bitpos = (USHORT)(pos & (BITPERDGT - 1));
USHORT m = 1U << bitpos;
if (shorts < DIGITS_L (a_l))
{
if (a_l[shorts + 1] & m)
{
res = 1;
}
a_l[shorts + 1] &= (USHORT)(~m);
RMLDZRS_L (a_l);
}
return res;
}
|
Team-Fly |