The so-called Bit-map is to use a bit bit to mark the value of an element, and key is the element. Because of the use of bit units to store data, the storage space can be greatly reduced. /* if N = 1; application memory space is int a[2]; Assuming that you need to sort or find the total number of n=10000000, then we need to apply the size of the memory space to int a[1 + N/32], where: a[0] accounted for 32 in memory for the decimal number 0-31, and so on: 1. Find the decimal 0-n corresponding to the subscript in array a: N/32 2. Find the number of 0-n corresponding to 0-31: n%32=m 3. Use shift 0-31 to make the corresponding 32bit bit 1:1<<>< p=""> <> Example: If you want to store 3 (1) a subscript 30/32 = 0; Placed in the a[0]; (2) 3% 32 = 30; (3) Shift left 30 bits 01000000 00000000 00000000 00000000 This corresponds to the value $a[0] = 1073741824; 1. Find the decimal 0-n corresponding to the subscript in the array A: Decimal 0-31, corresponding to A[0], the first conversion from the decimal number N to 32 of the remainder can be converted to the corresponding subscript in the array A. such as n=24, then n/32=0, then 24 corresponds to the subscript in array a is 0. Another example is n=60, then n/32=1, then 60 corresponds to the subscript in the array A is 1, so you can calculate the 0-n in the array a subscript. 2. Find the number of 0-n corresponding to 0-31: The decimal 0-31 corresponds to 0-31, and 32-63 corresponds to 0-31, that is, given a number n can be obtained by modulo 32 in the corresponding 0-31 of the number. 3. Use shift 0-31 to make the corresponding 32bit bit 1. Find the number corresponding to 0-31 m, left shift m bit: that is 2^m. Then set 1. Thus we calculate the space occupied by 10 million bit: 1byte = 8bit 1KB = 1024byte 1MB = 1024kb The space occupied is: 10000000/8/1024/1024MB. About 1MB more. */ Class Bigmap { Save with two bytes Private $mask = 0x1f; Private $bitsperword = 32; The number of bits shifted is 5 pow (2,5) = 32 Private $shift = 5; An array of stored data Public $bitArray = Array (); /** $i the corresponding number zero */ function Clearbit ($i) { Then the specified bit bit in the current byte is 0,& after the other array bit bit must be unchanged, this is the magical use of 1 $i >>shift here is equivalent to Intval ($i/32); $i & $this->mask is equivalent to $i% $this->mask @ $this->bitarray[$i >> $this->shift] &= ~ (1<< ($i & $this->mask)); } /** $i the corresponding number 1 */ function Setbit ($i) { @ $this->bitarray[$i >> $this->shift] |= (1<< ($i & $this->mask)); } Test where the bit 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); |