File tree Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Expand file tree Collapse file tree 1 file changed +23
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments