Flowdock
method

bit_length

Importance_2
v2_2_9 - Show latest stable - 0 notes - Class: Fixnum
bit_length() public

Returns the number of bits of the value of int.

“the number of bits” means that the bit position of the highest bit which is different to the sign bit. (The bit position of the bit 2**n is n+1.) If there is no such bit (zero or minus one), zero is returned.

I.e. This method returns ceil(log2(int < 0 ? -int : int+1)).

(-2**12-1).bit_length     #=> 13
(-2**12).bit_length       #=> 12
(-2**12+1).bit_length     #=> 12
-0x101.bit_length         #=> 9
-0x100.bit_length         #=> 8
-0xff.bit_length          #=> 8
-2.bit_length             #=> 1
-1.bit_length             #=> 0
0.bit_length              #=> 0
1.bit_length              #=> 1
0xff.bit_length           #=> 8
0x100.bit_length          #=> 9
(2**12-1).bit_length      #=> 12
(2**12).bit_length        #=> 13
(2**12+1).bit_length      #=> 13

This method can be used to detect overflow in Array#pack as follows.

if n.bit_length < 32
  [n].pack("l") # no overflow
else
  raise "overflow"
end
Show source
Register or log in to add new notes.