Alexandre
Alexandre

Reputation: 363

Ruby binary left shift

How to do a binary left shift in a integer value using Ruby?


I'm trying to do a left shift binary operation but I'm getting a strange char instead of the move..

I think that it should perform like this: (java)

b = (b >> 2); //0011 1111
b = (b << 2); //1111 1100

I'm doing this in ruby:

currentRed = ChunkyPNG::Color.r(image[x,y])
currentGreen = ChunkyPNG::Color.g(image[x,y])
currentBlue = ChunkyPNG::Color.b(image[x,y])

binRed = currentRed.to_s.unpack("b*")[0]
binGreen = currentGreen.to_s.unpack("b*")[0]
binBlue = currentBlue.to_s.unpack("b*")[0]

puts "original"

puts "r #{binRed}"
puts "g #{binGreen}"
puts "b #{binBlue}"

puts "------"

binRed = binRed << 2

binGreen = binGreen << 2
binBlue = binBlue << 2


puts "new"

puts "r #{binRed}"
puts "g #{binGreen}"
puts "b #{binBlue}"

and getting it:

enter image description here

thank you in advance..

Upvotes: 1

Views: 3204

Answers (2)

Mecki
Mecki

Reputation: 133079

In Ruby, << is a method. Actually most operators in Ruby are methods:

a = b << c
a = b + c
a = b ** c

# This is exactly the same as

a = b.<<(c)
a = b.+(c)
a = b.**(c)

You can even override them in your own classes to make them do whatever you want them to do. This is possibly as in Ruby everything (really everything) is an object under the hood (even classes and modules are objects, even nil is an object).

E.g. for a String the << method means append.

a = "Hello, " << "Word"
# a == "Hello, Word"

But in case of a Fixnum the << method just means shift left:

a = 5 << 2
# a == 20

So you are using the right "operator" but you need to make sure your objects are of the right class. You require integers which are of type Fixnum in Ruby.

And currentRed, currentBlue, and currentGreen are of type Fixnum already.

Upvotes: 2

Worakarn Isaratham
Worakarn Isaratham

Reputation: 1034

Your binRed, binGreen, binBlue are actually Strings, because b* unpack into bitstrings. For Strings, << means append, so no wonder the strange character (character code 2) got printed.

I'm not familiar with ChunkyPNG, but from the doc it looks like currentRed, currentGreen, currentBlue are already integers. You should be able to perform bit shift on them directly.

Upvotes: 4

Related Questions