binary

Bitmask and Bitwise Operations in Ruby

Here's a solution to a problem I was trying to solve in Ruby. I wanted to create a 23 bit data structure, that would hold three values. A 14 bit year, a 4 bit month and a 5 bit day. Each of these bit sizes are the minimum number of bits required to support a maximum value of 9999 for years, 12 for months and 31 for days (with months and days optional - hence the custom data structure). Using the bitwise & operator, you can either mask (protect) or zero out bit values. And then using the bitwise | operator - you can turn bits back on. In Ruby you can create and manipulate binary literals directly using the 0b prefix.

Category
Tags

Comments

Subscribe to binary