Fork me on GitHub

Project Notes

Bitwise Operations

All about bitwise operations in Ruby.

Notes

NOT

The ~ operator: one’s complement (returns a number where each bit is flipped)

By default, this returns a signed integer, so ~0b0101 produces -0b110. To convert to unsigned, & with 0xFFFF_FFFF

AND

The & operator: Bitwise AND.

OR

The [ ](https://ruby-doc.org/core-2.5.0/Integer.html#method-i-7C) operator: Bitwise OR.

XOR

The [^](https://ruby-doc.org/core-2.5.0/Integer.html#method-i-5E) operator: Bitwise EXCLUSIVE OR.

Shift

The « operator: shift left.

The » operator: shift right.

String Representation

The to_s(base=10) method. 3.to_s(2) => "11"

Example Code

The examples.rb file wraps up demonstrations of all these features in a set of tests. Not very exciting to run!

$ ruby examples.rb
Run options: --seed 42933

# Running:

.......

Finished in 0.001204s, 5813.9542 runs/s, 6644.5191 assertions/s.

7 runs, 8 assertions, 0 failures, 0 errors, 0 skips

Credits and References

About LCK#170 ruby
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.