File: utils.py

package info (click to toggle)
galileo 0.5.1-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 392 kB
  • ctags: 578
  • sloc: python: 3,462; xml: 23; makefile: 14
file content (68 lines) | stat: -rw-r--r-- 1,452 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""\
We internally use array of int as data representation, those routines
translate them to one or the other format
"""

import sys

def a2x(a, delim=' '):
    """ array to string of hexa
    delim is the delimiter between the hexa
    """
    return delim.join('%02X' % x for x in a)


def x2a(hexstr):
    """ String of hex a to array """
    return [int(x, 16) for x in hexstr.split(' ')]


def a2s(a, toPrint=True):
    """ array to string
    toPrint indicates that the resulting string is to be printed (stop at the
    first \0)
    """
    s = []
    for c in a:
        if toPrint and (c == 0):
            break
        s.append(chr(c))
    return ''.join(s)

def a2b(a):
    """ array to `bytes` """
    if sys.version_info > (3, 0):
        return bytes(a)
    return a2s(a, False)

def a2lsbi(array):
    """ array to int (LSB first) """
    integer = 0
    for i in range(len(array) - 1, -1, -1):
        integer *= 256
        integer += array[i]
    return integer


def a2msbi(array):
    """ array to int (MSB first) """
    integer = 0
    for i in range(len(array)):
        integer *= 256
        integer += array[i]
    return integer


def i2lsba(value, width):
    """ int to array (LSB first) """
    a = [0] * width
    for i in range(width):
        a[i] = (value >> (i*8)) & 0xff
    return a


def s2a(s):
    """ string to array """
    if isinstance(s, str):
        return [ord(c) for c in s]
    return [c for c in s]