Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,705 questions

55,464 answers

573 users

How to remove multiple bits from a number and shift the remaining bits right to fill the gaps in Ruby

1 Answer

0 votes
# remove_bits_and_shift(number, positions)
# ----------------------------------------
# Removes multiple bit positions from a number and shifts the remaining bits
# right to fill the gaps.
#
# Important:
#   Bits must be removed from highest → lowest position.
#   Otherwise earlier removals shift the positions of later ones.
def remove_bits_and_shift(number, positions) # number: Integer, positions: Array<Integer>
  sorted = positions.sort.reverse           # sort descending
  result = number                           # Integer

  sorted.each do |pos|
    left  = result >> (pos + 1)             # bits above removed bit
    right = result & ((1 << pos) - 1)       # bits below removed bit
    result = (left << pos) | right          # merge
  end

  result
end

# print_binary(n)
# ----------------
# Prints a 32-bit binary representation of an integer.
def print_binary(n) # n: Integer
  binary = "%032b" % n
  grouped = binary.scan(/.{4}/).join(" ")
  puts grouped
end

# Main program
number = 1234          # Integer
positions = [1, 3, 7]  # Array<Integer>

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

result = remove_bits_and_shift(number, positions)

puts "\nNumber after removing bits {1, 3, 7} and shifting remaining bits:"
print_binary(result)

puts "\nResult as integer: #{result}"



=begin
run:

Original number in binary:
0000 0000 0000 0000 0000 0100 1101 0010

Number after removing bits {1, 3, 7} and shifting remaining bits:
0000 0000 0000 0000 0000 0000 1001 0100

Result as integer: 148

=end

 



answered Jun 24 by avibootz

Related questions

...