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
28 # to binary level of Integer
29 # For compatibility reasons, xor, and, or methods
30 # are still in the math.nit module
33 # Sets the i-bit of self to the given value
34 # assert 11.setbit(0, 0) == 10
35 # assert 10.setbit(0, 1) == 11
36 fun setbit
(index
: Int, value
: Int): Int `{
37 assert(index >= 0 && index < 32);
40 return recv | (1 << index);
42 return recv & ~(1 << index);
45 # Returns the i-bit value of self Integer
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)
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
103 # set to 1 in self (the rightest bit is at position 0)
104 # assert 10.highest_bit == 3
105 # assert 1.highest_bit == 0
106 fun highest_bit
: Int `{
107 long int msb = 1L << 31;
110 while(msb > 0 && !(recv & msb))