English 中文(简体)
DWord 行动
原标题:DWord operations in Ruby

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

因此,我需要一种办法,与DWord的任何Bete(或Word)合作,并从事比照作业。

是否有任何人建议采用一种方法,将4个沥青阵列转换为DWord,然后使用Bytes,从而产生DWord?

最佳回答

你可以总结一下你在课堂上的逻辑。 这里是一个脱节的例子(需要加上边界和错误检查)。

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

你可以做与Word、QWord等类似的事情。 以上将允许你这样做:

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   
问题回答

页: 1

"101".to_i(2) => 5

以及

5.to_s(2) => "101"

很容易转化成其他基地(其基础是论点)。

See http://www.ruby-doc.org/core/classes/String.html#M000802

借用你的号码,

See http://www.tutorialspoint.com/ruby/ruby_operators.htm

并检查Ruby BilwiseOperationtors

首先,将阵列转化为你能够做到的ice:

puts [255,1,255,2].map{|val| val.to_s(2).rjust(8,  0 )}.join(   )

对双轨业务来说,这很简单。 它使用C类经营者:

OR => 1 | 2 = 3
AND => 1 & 2 = 0
XOR => 1 ^ 3 = 2 

http://en.wikipedia.org/wiki/Bitwise_operation”rel=“nofollow”





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签