Code archives/Algorithms/Set individual bits in a bank
This code has been declared by its author to be Public Domain code.
Download source code
| |||||
B3D only allows you to read or write to a bank in multiples of 8 bits. *Byte(8 bits) *Short(16 bits) *Int(32 bits) These functions simply enable you to write and read individual bits in a bank(up to 255MB in size). It also enables you to read the last bit position in the bank. It can be useful for bit flags or compression. Functions: bit_read(bank, offset%) *Returns the bit at offset% of bank *offset% should be of type Int bit_write(bank, offset%, bit) *Writes the bit at offset% of bank with a bit value of either 0 or 1 *offset% should be of type Int bit_last(bank) *Returns the last bit in bank, effectively the size in bits-1. Usage: bank - the name of the bank you wish to manipulate. offset% - the position of the bit you wish to set. bit - the binary value you want the bit to have(0 or 1). Remember that offset% begins at 0. | |||||
; Create the bank to use bnktest=CreateBank(120) ; set the first 16 bits of the bank to alternating 1/0 For q%=0 To 15 Step 2 bit_write(bnktest, q%, 1) Next ; Read and display the first 16 bits of the bank For q%= 0 To 15 a=bit_read(bnktest,q%) Print a Next Print ; Read and display the last bit position in the bank Print "The last bit position in bank is "+bit_last(bnktest) WaitKey() Function bit_read(bank, offset%) b=offset% Mod 8 c%=(offset%-b)/8 a=PeekByte(bank,c%) Return (a Shr (b )) And 1 End Function Function bit_write(bank, offset%, bit) b=offset% Mod 8 c%=(offset%-b)/8 a=PeekByte(bank,c%) If bit <>0 Then a=a Or (bit Shl (b)) Else a=a And (bit Shl (b)) EndIf PokeByte bank,c%,a End Function Function bit_last(bank) a%=BankSize(bank)*8 Return a%-1 End Function |
Comments
None.
Code Archives Forum