TheAlgorithms-Ruby/bit_manipulation/binary_and_operator.rb

24 lines
419 B
Ruby
Raw Normal View History

2021-05-01 23:38:17 +02:00
def binary_and(x, y)
2021-09-03 22:24:58 +02:00
raise 'Input must only contain positive integers' if (x < 0) || (y < 0)
2021-05-01 23:38:17 +02:00
2021-09-03 22:24:58 +02:00
'0b' + (x & y).to_s(2)
2021-05-01 23:38:17 +02:00
end
begin
binary_and(-1, 0)
2021-09-03 22:24:58 +02:00
rescue StandardError => e
2021-05-01 23:38:17 +02:00
puts e.message
end
# Input must only contain positive integers
2021-05-01 23:38:17 +02:00
puts binary_and(1, 1)
# 0b1
puts binary_and(0, 1)
# 0b0
puts binary_and(1024, 1024)
# 0b10000000000
puts binary_and(0, 1023)
# 0b0000000000
puts binary_and(16, 58)
# 0b010000