How do I set a specific bit in an integer

  • Thread starter Thread starter Ina
  • Start date Start date
I

Ina

I would like to use an integer as 16 individual bits. How
do I set/reset a bit without affecting the other bit-
values?

Like my integer is:

0010 0111 0001 1101

and I would like to set the 15th bit:

0010 0111 0001 1111

or I would like to reset the 13th bit:

0010 0111 0001 0101
 
IN VBA code, use the binary And operator to read the bit, or the Or operator
to set it.

Example of reading the 15th bit (most significant bit apart from the sign):
? &H7fff And 2^14
and setting the 15th bit:
? 1 Or 2^14
 
I have a function like you describe below to get the bit
value:

Public Function GetBit(bitno As Byte, bits As Integer) As
Boolean
GetBit = CBool(bits And 2 ^ bitno)
End Function

Now I would like to have a function
SetBit(bitno as byte, bit as boolean, bits as integer) as
integer

This bunction should set the "bitno" bit to 0 or 1 in the
integer "bits".

but I dont quite manage to get it working as per your
description. Any help?
 
solved it:

Public Function SetBit(bitno As Byte, bit As Boolean, bits
As Integer) As Integer
If bit Then
SetBit = CInt(bits Or 2 ^ bitno)
Else
SetBit = CInt(bits And (bits Xor 2 ^ bitno))
End If
End Function
 
Ina said:
solved it:

Public Function SetBit(bitno As Byte, bit As Boolean, bits
As Integer) As Integer
If bit Then
SetBit = CInt(bits Or 2 ^ bitno)
Else
SetBit = CInt(bits And (bits Xor 2 ^ bitno))


That will work, but are you sure you want to use the Integer
type for this? Think about using Long instead.

Also, you may find this to be a little less obscure:

Else
SetBit = CInt(bits And (Not 2 ^ bitno))
 
I would like to use an integer as 16 individual bits.

Why (1)? Access will manage several Boolean fields better than you, and can
take over all the read/ save functions properly. All your queries will
become non-updateable. If you are worried about disk storage space, then
the amount saved will be pretty trivial; if you are really that close to
2GB then you should be thinking about moving up to a real DBMS (in which
case, most of them will pack several bit columns into a smaller space
anyway, so you are still back to square one).

Why (2)? A long series of similar fields begs to be normalised. What about
a new table and 16 _records_ with one bit field in each?

Just a thought


Tim F
 
Back
Top