2013-10-08 60 views
0

如何使用Ruby在整數值中執行二進制左移?紅寶石二進制左移


我試圖做一個左移二元運算,但我發現一個奇怪的字符 而不是移動..

我認爲應該這樣進行:(JAVA)

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

我在紅寶石這樣做:

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}" 

,並得到它:

enter image description here

預先感謝您..

+1

你的問題是什麼? – sawa

+0

如何將rgb值轉換爲整數二進制形式?我嘗試將rgb值轉換爲二進制形式,如下所示:binRed = currentRed.to_s(2) \t binGreen = currentGreen.to_s(2) \t binBlue = currentBlue.to_s(2)但我得到了與在printscreen中相同的結果上面..因爲它們仍然是字符串.. – Alexandre

回答

4

binRedbinGreenbinBlue其實是Strings,因爲b*解壓到bitstring。對於字符串,<<表示追加,所以難怪打印出奇怪的字符(字符編碼2)。

我不熟悉ChunkyPNG,但從doc看起來像currentRed,currentGreen,currentBlue已經是整數。你應該能夠直接對它們進行位移。

+0

謝謝Worakam,你是對的..是yes currentRed,currentGreen和currentBlue是整數,但它們是rgb值,我需要將它們轉換爲二進制,然後執行位移...... do你知道如何做到這一點? – Alexandre

+0

您不需要將它們轉換爲二進制文件(因爲它們在引擎蓋下已經是二進制文件)。只要執行'currentRed << 2',它就會向左移2位......如果你想像原來一樣將它們截斷爲24位,你可以用0xFFFFFF來掩蓋它們。所以'currentRed =(currentRed << 2)&0xFFFFFF'應該滿足你的需要。 –

+0

這樣做我有:--------- 原 [R 253 摹253 b 253 ------ 新 [R 1012 摹1012 b 1012 這是正確的?我需要做左移,因爲我正在嘗試執行最後一個重要的位更改,以便將數據放入png中。 – Alexandre