5.17. Performing Bit-level Operations on Numbers

Occasionally we may need to operate on a Fixnum as a binary entity. This is less common in application level programming, but the need still arises.

Ruby has a relatively full set of capabilities in this area. For convenience, numeric constants may be expressed in binary, octal, or hexadecimal. The usual operators AND, OR, XOR, and NOT are expressed by the Ruby operators &, |, ^, and ~, respectively.

x = 0377           # Octal  (decimal 255)
y = 0b00100110     # Binary (decimal  38)
z = 0xBEEF         # Hex    (decimal 48879)

a = x | z          # 48895 (bitwise OR)
b = x & z          #   239 (bitwise AND)
c = x ^ z          # 48656 (bitwise XOR)
d = ~ y            #   -39 (negation or 1's complement)

The instance method size can be used to determine the word size ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.