Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Created March 1, 2015 09:07
Show Gist options
  • Save ifyouseewendy/340a95c40ffdcce8decd to your computer and use it in GitHub Desktop.
Save ifyouseewendy/340a95c40ffdcce8decd to your computer and use it in GitHub Desktop.

from Binary and Bitwise Operations in Ruby by CooperPress http://goo.gl/4uQY7f

Bitwise

Representation

How to represent base 2, 8, 10, 16 in Integer?

0b1010
012
10
0xA

How to represent base 2, 8, 10, 16 in String?

"1010"
"12"
"10"
"A"

Exchange

How to change representation from Integer to String?

0b1010.to_s(2) # => "1010"
012.to_s(8)    # => "12"
10.to_s        # => "10"
0xA.to_s(16)   # => "A"

How to change representation from String to Integer?

"1010".to_i(2) # => 10
"12".to_i(8)   # => 10
"10".to_i      # => 10
"A".to_i(16)   # => 10

Operation

  • and, &
  • or, |
  • xor, ^
  • not, ~
  • shift, <<, >>
(0b101 & 0b110).to_s(2) # => "100"
(0b101 | 0b110).to_s(2) # => "111"
(0b101 ^ 0b110).to_s(2) # => "11"
(~0b101).to_s(2)        # => "-110"
(0b101 << 1).to_s(2)    # => "1010"
(0b1010 >> 1).to_s(2)   # => "101"

Usage

Use >> and << to multiply or divide by 2.

24 << 1                 # => 48
24 << 2                 # => 96
37 >> 1                 # => 18

Use & as a mask.

"01101001".to_i(2)      # => 105

0b11110000 & 0b01101001 # => 96
96 >> 4                 # => 6

0b00001111 & 0b01101001 # => 9

Use &, | and ^ to check, set, unset a state.

PRIVATE   = 1
PUBLISHED = 2
DELETED   = 4

flags = 0

# use | to set a state
flags |= PRIVATE        # => 1
flags |= PUBLISHED      # => 3

# use & to check a state
flags & PRIVATE         # => 1
flags & PUBLISHED       # => 2
flags & DELETED         # => 0

# use ^ to unset a state
flags ^= PRIVATE        # => 2
flags &  PRIVATE        # => 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment