Mega Code Archive

 
Categories / Ruby / Language Basics
 

Do bitwise operations in Ruby

A bitwise operation operates on each bit, bit for bit, rather than on the numeral as a single unit.  Bitwise operations are often faster than regular arithmetic operations.  puts ~1011 # bitwise not or complement puts 1011 | 1010 # bitwise or puts 1011 & 1010 # bitwise and puts 1011 ^ 1010 # bitwise exclusive or puts 1011 << 1 # shift left puts 1011 >> 1 # shift right