Module: Orchestrator::Transcoder

Included in:
Device::Processor
Defined in:
lib/orchestrator/utilities/transcoder.rb

Class Method Summary collapse

Class Method Details

.array_to_str(data) ⇒ String

Converts a byte array into a binary string

Parameters:

  • data (Array)

    an array of bytes

Returns:

  • (String)


49
50
51
52
# File 'lib/orchestrator/utilities/transcoder.rb', line 49

def array_to_str(data)
    return data if data.is_a? String
    data.pack('c*')
end

.byte_to_hex(data) ⇒ String

Converts a binary string into a hex encoded string

Parameters:

  • data (String)

    a binary string

Returns:

  • (String)


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/orchestrator/utilities/transcoder.rb', line 24

def byte_to_hex(data)
    data = array_to_str(data) if data.is_a? Array

    output = ""
    data.each_byte { |c|
        s = c.to_s(16)
        s.prepend('0') if s.length % 2 > 0
        output << s
    }
    return output
end

.hex_to_byte(data) ⇒ String

Converts a hex encoded string into a binary string

Parameters:

  • data (String)

    a hex encoded string

Returns:

  • (String)


7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/orchestrator/utilities/transcoder.rb', line 7

def hex_to_byte(data)
    # Removes invalid characters
    data = data.gsub(/(0x|[^0-9A-Fa-f])*/, "")

    # Ensure we have an even number of characters
    data.prepend('0') if data.length % 2 > 0

    # Breaks string into an array of characters
    output = []
    data.scan(/.{2}/) { |byte| output << byte.hex}
    output.pack('c*')
end

.str_to_array(data) ⇒ Array

Converts a string into an array of bytes

Parameters:

  • data (String)

    data to be converted to bytes

Returns:

  • (Array)


40
41
42
43
# File 'lib/orchestrator/utilities/transcoder.rb', line 40

def str_to_array(data)
    return data if data.is_a? Array
    data.bytes.to_a
end