How to remove a bit from a number and shift all bits to the right to fill the gap in Ruby

1 Answer

0 votes
# Removes the bit at the given position and shifts all higher bits right.
def remove_bit_and_shift(number, position)
  #
  # number = 22 (10110)
  # position = 2 (0 = LSB)
  #
  # Bits: 1 0 1 1 0
  #           ^ remove this bit
  #
  # left  = bits above removed bit
  # right = bits below removed bit
  #
  # result = (left << position) | right
  #

  left  = number >> (position + 1)          # bits above removed bit
  right = number & ((1 << position) - 1)    # bits below removed bit

  (left << position) | right                # merge shifted left + right
end

# Prints a 32-bit binary representation of an integer.
def print_binary(value)
  #
  # Uses:
  #   value.to_s(2) → binary string
  #   rjust(32, "0") → pad to 32 bits
  #   scan(/.{1,4}/) → group into 4-bit chunks
  #

  binary = value.to_s(2).rjust(32, "0")
  grouped = binary.scan(/.{1,4}/).join(" ")
  puts grouped
end

# Main program
number = 22
position = 2  # remove bit 2 (0 = LSB)

puts "Original number in binary:"
print_binary(number)

result = remove_bit_and_shift(number, position)

puts
puts "Number after removing bit #{position} and shifting remaining bits:"
print_binary(result)

puts
puts "Result as integer: #{result}"



=begin
run:

Original number in binary:
0000 0000 0000 0000 0000 0000 0001 0110

Number after removing bit 2 and shifting remaining bits:
0000 0000 0000 0000 0000 0000 0000 1010

Result as integer: 10

=end

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz

Related questions

...