|
// The so-called Bit-map uses a bit to mark the Value corresponding to an element, and the Key is the element. Because Bit is used to store data, the storage space can be greatly reduced.
/*
If N = 1; the applied memory space is int a [2];
Assuming that the total number of tasks to be sorted or queried is N = 10000000, we need to apply for the memory size to be int a [1 + N/32], where: a [0] 32 in memory can correspond to 0-31 decimal numbers, and so on:
1. calculate the subscript corresponding to decimal 0-n in array a: n/32
2. calculate the number in 0-31 corresponding to 0-N: N % 32 = M
3. use shift 0-31 to set the corresponding 32bit to 1: 1 < < p> <>
Example:
If you want to store 3
(1) a subscript 30/32 = 0; put it in a [0;
(2) 3% 32 = 30;
(3) shift 30 digits left 01000000 00000000 00000000 00000000 corresponding value $ a [0] = 1073741824;
1. calculate the subscript corresponding to decimal 0-n in array:
Decimal 0-31, corresponding to a [0], first converted from the decimal number n to the remainder of 32 can be converted to the subscript corresponding to array. For example, if n = 24, then n/32 = 0, then the subscript of 24 in array a is 0. For example, if n = 60, then n/32 = 1, 60 corresponds to the subscript of 1 in array a. Similarly, 0-n in array a can be computed.
2. calculate the number 0-n corresponding to 0-31:
0-31 corresponds to 0-31, while 32-63 corresponds to 0-31. given a number n, the number corresponding to 0-31 can be obtained through modulo 32.
3. use shift 0-31 to set the corresponding 32bit to 1.
Find the number of M corresponding to 0-31, and move M to the left: 2 ^ M. then set 1.
Therefore, we can calculate the space occupied by 10000000 bits:
1 byte = 8bit
1kb = 1024 bytes
1 mb = 1024kb
The occupied space is 10000000/8/1024/1024 mb.
About 1 MB.
*/
Class bigMap {
// Save in two bytes
Private $ mask = 0x1f;
Private $ bitsperword = 32;
// The number of shifts is 5 pow () = 32
Private $ shift = 5;
// Array of stored data
Public $ bitArray = array ();
/**
$ I returns to zero.
*/
Function clearbit ($ I ){
/// The specified bit in the current byte is taken as 0, and the bit in the other array of the other side will inevitably remain unchanged. this is a wonderful use of 1.
// $ I> SHIFT here is equivalent to intval ($ I/32 );
// $ I & $ this-> mask is equivalent to $ I % $ this-> mask here, taking the remainder
@ $ This-> bitArray [$ I >>$ this-> shift] & = ~ (1 <($ I & $ this-> mask ));
}
/**
$ I corresponds to 1
*/
Function setbit ($ I ){
@ $ This-> bitArray [$ I >$ this-> shift] | = (1 <($ I & $ this-> mask ));
}
// Test whether the bit of the test is 1
Function testbit ($ I ){
Return $ this-> bitArray [$ I >$ this-> shift] & (1 <($ I & $ this-> mask ));
}
}
$ OBig = new bigMap ();
$ OBig-> setbit (30 );
Var_dump ($ oBig-> testbit (2 ));
Var_dump ($ oBig-> bitArray );
|