Ruby - Bitwise operators

1. Introduction

Bitwise operators are used to perform binary (bit-level) operations on integer operands. These operations are fundamental in lower-level programming, particularly for tasks such as manipulating flags, working with binary data formats, or network protocols.

2. Program Steps

1. Initialize sample variables.

2. Apply and demonstrate the bitwise operators on the initialized variables.

3. Code Program

# Initialize sample variables
a = 60 # binary: 111100
b = 13 # binary: 001101
# Bitwise AND
and_result = a & b
puts "Bitwise AND: #{a.to_s(2)} & #{b.to_s(2)} = #{and_result.to_s(2)}"
# Bitwise OR
or_result = a | b
puts "Bitwise OR: #{a.to_s(2)} | #{b.to_s(2)} = #{or_result.to_s(2)}"
# Bitwise XOR
xor_result = a ^ b
puts "Bitwise XOR: #{a.to_s(2)} ^ #{b.to_s(2)} = #{xor_result.to_s(2)}"
# Bitwise NOT
not_result = ~a
puts "Bitwise NOT: ~#{a.to_s(2)} = #{not_result.to_s(2)}"
# Left Shift
left_shift_result = a << 2
puts "Left Shift: #{a.to_s(2)} << 2 = #{left_shift_result.to_s(2)}"
# Right Shift
right_shift_result = a >> 2
puts "Right Shift: #{a.to_s(2)} >> 2 = #{right_shift_result.to_s(2)}"

Output:

Bitwise AND: 111100 & 001101 = 001100
Bitwise OR: 111100 | 001101 = 111101
Bitwise XOR: 111100 ^ 001101 = 110001
Bitwise NOT: ~111100 = -111101
Left Shift: 111100 << 2 = 11110000
Right Shift: 111100 >> 2 = 001111

Explanation:

1. The Bitwise AND (&) operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1; otherwise, the corresponding result bit is set to 0.

2. The Bitwise OR (|) operator compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1; otherwise, the corresponding result bit is set to 0.

3. The Bitwise XOR (^) operator compares each bit of the first operand to the corresponding bit of the second operand. If the bits are different, the corresponding result bit is set to 1; otherwise, the corresponding result bit is set to 0.

4. The Bitwise NOT (~) operator inverts the bits of its operand.

5. The Left Shift (<<) operator shifts the bits of its first operand to the left by the number of positions specified by its second operand, filling in zeros from the right.

6. The Right Shift (>>) operator shifts the bits of its first operand to the right by the number of positions specified by its second operand, filling in the original leftmost bit (sign bit) into the left positions.


Comments