d4e2f190383491f5d2d09d64baaee3703d62384e
[zxing.git] / core / src / com / google / zxing / common / BitArray.java
1 /*\r
2  * Copyright 2007 Google Inc.\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *      http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package com.google.zxing.common;\r
18 \r
19 /**\r
20  * <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p>\r
21  *\r
22  * @author srowen@google.com (Sean Owen)\r
23  */\r
24 public final class BitArray {\r
25 \r
26   private final int[] bits;\r
27 \r
28   public BitArray(int size) {\r
29     int arraySize = size >> 5;\r
30     if ((size & 0x1F) != 0) {\r
31       arraySize++;\r
32     }\r
33     bits = new int[arraySize];\r
34   }\r
35 \r
36   /**\r
37    * @param i bit to get\r
38    * @return true iff bit i is set\r
39    */\r
40   public boolean get(int i) {\r
41     return (bits[i >> 5] & (1 << (i & 0x1F))) != 0;\r
42   }\r
43 \r
44   /**\r
45    * Sets bit i.\r
46    *\r
47    * @param i bit to set\r
48    */\r
49   public void set(int i) {\r
50     bits[i >> 5] |= 1 << (i & 0x1F);\r
51   }\r
52 \r
53   /**\r
54    * Sets a block of 32 bits, starting at bit i.\r
55    *\r
56    * @param i first bit to set\r
57    * @param newBits the new value of the next 32 bits. Note again that the least-significant bit\r
58    *  correponds to bit i, the next-least-significant to i+1, and so on.\r
59    */\r
60   public void setBulk(int i, int newBits) {\r
61     bits[i >> 5] = newBits;\r
62   }\r
63 \r
64   /**\r
65    * Clears all bits (sets to false).\r
66    */\r
67   public void clear() {\r
68     int max = bits.length;\r
69     for (int i = 0; i < max; i++) {\r
70       bits[i] = 0;\r
71     }\r
72   }\r
73 \r
74   /**\r
75    * @return underlying array of ints. The first element holds the first 32 bits, and the least\r
76    *  significant bit is bit 0.\r
77    */\r
78   public int[] getBitArray() {\r
79     return bits;\r
80   }\r
81 \r
82 }