Skip to content

Commit 5aca267

Browse files
committed
Added & and ^ explanations
1 parent 68a4f3b commit 5aca267

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

special_ops.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# & is the bitwise and operation. It operates on numbers in their binary representation.
2+
# It takes a pair of bits at a given position in the input numbers and
3+
# puts a 1 in that position in the output if they are both 1s. Otherwise
4+
# it puts a 0.
5+
def bitwise_and(x, y)
6+
ans = x&y
7+
# rjust(5) pads the string with spaces (on the left) up to a length of 5
8+
puts x.to_s.rjust(5) + " = " + x.to_s(2).rjust(8,'0')
9+
puts y.to_s.rjust(5) + " = " + y.to_s(2).rjust(8,'0')
10+
puts (x.to_s + "&" + y.to_s).rjust(5) + " = " + ans.to_s(2).rjust(8, '0') + " = " + ans.to_s
11+
end
12+
13+
# ^ is the bitwise xor operation. It operates on numbers in their binary representation.
14+
# It takes a pair of bits at a given position in the input numbers and
15+
# puts a 1 in that position in the output if exactly one is a 1. Otherwise
16+
# it puts a 0.
17+
def bitwise_xor(x, y)
18+
ans = x^y
19+
# rjust(5) pads the string with spaces (on the left) up to a length of 5
20+
puts x.to_s.rjust(5) + " = " + x.to_s(2).rjust(8,'0')
21+
puts y.to_s.rjust(5) + " = " + y.to_s(2).rjust(8,'0')
22+
puts (x.to_s + "^" + y.to_s).rjust(5) + " = " + ans.to_s(2).rjust(8, '0') + " = " + ans.to_s
23+
end

0 commit comments

Comments
 (0)