How do you find the position of the most significant bit (MSB) of an unsigned integer in Ruby

2 Answers

0 votes
# Returns the zero-based position of the most significant set bit (MSB)
# in a non-negative integer.
#
# Examples:
#   1  -> 0
#   2  -> 1
#   8  -> 3
#   15 -> 3
#
# @param value [Integer]
#   A non-negative integer.
#
# @return [Integer]
#   The zero-based position of the highest set bit.
#   Returns -1 if value is 0.
#
# @raise [ArgumentError]
#   If value is negative.
def msb_position(value)
  raise ArgumentError, 'value must be a non-negative integer' if value.negative?

  return -1 if value.zero?

  value.bit_length - 1
end

# Application entry point.
def main
  test_values = [
    0,
    1,
    2,
    8,
    15,
    0x1234,
    0x8000_0000
  ]

  test_values.each do |value|
    position = msb_position(value)

    if position >= 0
      puts "Value: #{value}, MSB position: #{position}"
    else
      puts "Value: #{value}, no bits are set"
    end
  end
end

main if __FILE__ == $PROGRAM_NAME



# run:
#
# Value: 0, no bits are set
# Value: 1, MSB position: 0
# Value: 2, MSB position: 1
# Value: 8, MSB position: 3
# Value: 15, MSB position: 3
# Value: 4660, MSB position: 12
# Value: 2147483648, MSB position: 31
# 

 



answered Oct 1 by avibootz
0 votes
# Returns the zero-based position of the most significant set bit (MSB)
# in a non-negative integer.
#
# Examples:
#   1  -> 0
#   2  -> 1
#   8  -> 3
#   15 -> 3
#
# @param value [Integer]
#   A non-negative integer.
#
# @return [Integer]
#   The zero-based position of the highest set bit.
#   Returns -1 if value is 0.
#
# @raise [ArgumentError]
#   If value is negative.
def msb_position(value)
  raise ArgumentError, 'value must be a non-negative integer' if value.negative?

  return -1 if value.zero?

  position = 0

  while value > 1
    value >>= 1
    position += 1
  end

  position
end

# Application entry point.
def main
  test_values = [
    0,
    1,
    2,
    8,
    15,
    0x1234,
    0x8000_0000
  ]

  test_values.each do |value|
    position = msb_position(value)

    if position >= 0
      puts "Value: #{value}, MSB position: #{position}"
    else
      puts "Value: #{value}, no bits are set"
    end
  end
end

main if __FILE__ == $PROGRAM_NAME



# run:
#
# Value: 0, no bits are set
# Value: 1, MSB position: 0
# Value: 2, MSB position: 1
# Value: 8, MSB position: 3
# Value: 15, MSB position: 3
# Value: 4660, MSB position: 12
# Value: 2147483648, MSB position: 31
# 

 



answered Oct 1 by avibootz
...