I'm looking for ways of converting an array of byte values in DWord using Ruby.
For example: [255,1,255,2] -> 11111111 00000001 11111111 000000010
And then I need a way to work with any Byte(or Word) from this DWord and perform bit-wise operations.
Can anyone sugges开发者_如何学编程t a method for converting 4 byte array to DWord and then accessing Bytes in resulting DWord?
You can encapsulate your logic in classes. Here is a stripped-down example (would need to add boundary- and error-checking).
class Byte
attr_accessor :value
def initialize(integer)
@value = integer
end
def to_s
value.to_s(2).rjust(8,"0")
end
end
class DWord
attr_accessor :bytes
def initialize(*byte_list)
@bytes = []
byte_list.each do |b|
@bytes << Byte.new(b)
end
end
def to_s
@bytes.map(&:to_s).join(' ')
end
end
You could do something similar for Word, QWord, etc. The above will allow you to do this:
dword = DWord.new(255,1,255,2)
puts dword
# 11111111 00000001 11111111 00000010
dword.bytes.each do |b|
puts "#{b.value} = #{b}"
end
# 255 = 11111111
# 1 = 00000001
# 255 = 11111111
# 2 = 00000010
you can use
"101".to_i(2) => 5
and
5.to_s(2) => "101"
to convert to other bases pretty easily (the base is the argument)
See http://www.ruby-doc.org/core/classes/String.html#M000802
For bit operations on your numbers,
See http://www.tutorialspoint.com/ruby/ruby_operators.htm
And check the chapter Ruby Bitwise Operators
First to convert the array of into into a nice string you can do that:
puts [255,1,255,2].map{|val| val.to_s(2).rjust(8, '0')}.join(' ')
For the binary operations it's pretty simple. It uses the C based operators:
OR => 1 | 2 = 3
AND => 1 & 2 = 0
XOR => 1 ^ 3 = 2
You should not be using strings for bitwise operations...
精彩评论