Class: Digiproc::Strategies::GrayCode
- Inherits:
-
Object
- Object
- Digiproc::Strategies::GrayCode
- Defined in:
- lib/strategies/code/gray_code.rb
Overview
Strategy for creating the Gray Code of a big stream. Capable of encoding or decoding gray code Gray code ensures that all adjacent numbers only differ by one bit. This will reduce errors caused by a transmission/recieving process For information on Gray Code, try looking at www.allaboutcir- cuits.com/technical-articles/gray-code-basics/
Class Method Summary collapse
-
.generate(size) ⇒ Object
Input argument = integer indicating how many bits you want The output will be an array of incrememnting gray code numbers with the number of specified bits.
-
.to_binary(bin) ⇒ Object
Accepts a n integer.
-
.to_dec(bin) ⇒ Object
Accepts a n integer.
-
.to_gray(binary) ⇒ Object
Accepts a n integer.
Class Method Details
.generate(size) ⇒ Object
Input argument = integer indicating how many bits you want The output will be an array of incrememnting gray code numbers with the number of specified bits. The output array’s length wlll be 2^n where ‘n` is the input number.
15 16 17 18 19 20 21 |
# File 'lib/strategies/code/gray_code.rb', line 15 def self.generate(size) if size == 1 ["0", "1"] else prepend("0", generate(size - 1)) + prepend("1", generate(size - 1).reverse) end end |
.to_binary(bin) ⇒ Object
Accepts a n integer. The input integer is the decimal version of a gray code number This method will output a binary number in string form The ouput number is the “regular” number counterpart to the gray code input number. The output will be in binary form.
29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/strategies/code/gray_code.rb', line 29 def self.to_binary(bin) bits = bin.size gray_code = 0 bit_number = bits - 1 bit = 0 while bit_number >= 0 bit ^= bin >> bit_number & 1 gray_code |= (1 << bit_number) * bit bit_number -= 1 end gray_code.to_s(2) end |
.to_dec(bin) ⇒ Object
Accepts a n integer. The input integer is the decimal version of a gray code number This method will output a decimal number in string form The ouput number is the “regular” number counterpart to the gray code input number. The output will be in decimal form.
48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/strategies/code/gray_code.rb', line 48 def self.to_dec(bin) bits = bin.size gray_code = 0 bit_number = bits - 1 bit = 0 while bit_number >= 0 bit ^= bin >> bit_number & 1 gray_code |= (1 << bit_number) * bit bit_number -= 1 end gray_code.to_s end |
.to_gray(binary) ⇒ Object
Accepts a n integer. The input integer is a decimal number that you want to convert to gray code This method will output a binary number in string form The ouput number is the the gray code number counterpart to the input integer.
66 67 68 |
# File 'lib/strategies/code/gray_code.rb', line 66 def self.to_gray(binary) (binary ^ (binary >> 1)).to_s(2) end |