6794dcbdb617d7e007a04b552f4f0fd39a86f287
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
28 # Add support of binary operations related
29 # to binary level of Integer
30 # For compatibility reasons, xor, and, or methods
31 # are still in the math.nit module
34 # Sets the i-bit of self to the given value
35 # assert 11.setbit(0, 0) == 10
36 # assert 10.setbit(0, 1) == 11
37 fun setbit
(index
: Int, value
: Int): Int `{
38 assert(index >= 0 && index < 32);
41 return recv | (1 << index);
43 return recv & ~(1 << index);
46 # Returns the i-bit value of self Integer
47 # assert 10.getbit(0) == 0
48 # assert 10.getbit(3) == 1
49 fun getbit
(index
: Int): Int `{
50 assert(index >= 0 && index < 32);
60 # Give a binary representation of self Integer
63 var bits
= new Array[Int].with_capacity
(32)
73 # Returns the number of bits of specified value (0 or 1)
75 # assert 10.number_bits(1) == 2
76 # assert 10.number_bits(0) == 30
77 fun number_bits
(value
: Int): Int `{
78 assert(value == 0 || value == 1);
80 long int bound = 1L << 31;
86 for(i=bound; i>0; i/=2)
94 for(i=bound; i>0; i/=2)
103 # Returns the position of the highest bit
104 # set to 1 in self (the rightest bit is at position 0)
105 # assert 10.highest_bit == 3
106 # assert 1.highest_bit == 0
107 fun highest_bit
: Int `{
108 long int msb = 1L << 31;
111 while(msb > 0 && !(recv & msb))