1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Copyright 2014 Julien Pagès <julien.pages@lirmm.fr>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Services to handle BitSet
27 # Add support of binary operations related to binary level of Integer
28 # For compatibility reasons, xor, and, or methods are still in the `math` module.
31 # Sets the i-bit of self to the given `value`
33 # assert 11.setbit(0, 0) == 10
34 # assert 10.setbit(0, 1) == 11
35 fun setbit
(index
: Int, value
: Int): Int `{
36 assert(index >= 0 && index < 32);
39 return self | (1 << index);
41 return self & ~(1 << index);
44 # Returns the i-bit value of `self`
46 # assert 10.getbit(0) == 0
47 # assert 10.getbit(3) == 1
48 fun getbit
(index
: Int): Int `{
49 assert(index >= 0 && index < 32);
59 # Give a binary representation of self Integer
62 var bits
= new Array[Int].with_capacity
(32)
72 # Returns the number of bits of specified value (0 or 1) in `self`
74 # assert 10.number_bits(1) == 2
75 # assert 10.number_bits(0) == 30
76 fun number_bits
(value
: Int): Int `{
77 assert(value == 0 || value == 1);
79 long int bound = 1L << 31;
85 for(i=bound; i>0; i/=2)
93 for(i=bound; i>0; i/=2)
102 # Returns the position of the highest bit set to 1 in `self`
104 # The rightmost bit is at position 0.
106 # assert 10.highest_bit == 3
107 # assert 1.highest_bit == 0
108 fun highest_bit
: Int `{
109 long int msb = 1L << 31;
112 while(msb > 0 && !(self & msb))