byte_swap.byte_swap_32_bit()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 14
rs 9.85
c 0
b 0
f 0
cc 3
nop 1
1
import struct
2
########################################################################################################################
3
# Swap adjacent bytes
4
# This is not big-endian and little-endian swapping.
5
########################################################################################################################
6
7
8
# swap adjacent bytes of 32bits (4bytes) data,
9
# abcd => badc
10
def byte_swap_32_bit(x):
11
    x_type = type(x)
12
    if x_type is float:
13
        x = struct.unpack('>I', struct.pack('>f', x))[0]
14
15
    a = ((x >> 8) & 0x00FF0000)
16
    b = ((x << 8) & 0xFF000000)
17
    c = ((x >> 8) & 0x000000FF)
18
    d = ((x << 8) & 0x0000FF00)
19
20
    if x_type is float:
21
        return struct.unpack('>f', struct.pack('>I', b | a | d | c))[0]
22
    else:
23
        return b | a | d | c
24
25
26
# swap adjacent bytes of 64bits (8bytes) data,
27
# abcdefgh => badcfehg
28
def byte_swap_64_bit(x):
29
    x_type = type(x)
30
    if x_type is float:
31
        x = struct.unpack('>Q', struct.pack('>d', x))[0]
32
33
    a = ((x >> 8) & 0x00FF000000000000)
34
    b = ((x << 8) & 0xFF00000000000000)
35
    c = ((x >> 8) & 0x000000FF00000000)
36
    d = ((x << 8) & 0x0000FF0000000000)
37
    e = ((x >> 8) & 0x0000000000FF0000)
38
    f = ((x << 8) & 0x00000000FF000000)
39
    g = ((x >> 8) & 0x00000000000000FF)
40
    h = ((x << 8) & 0x000000000000FF00)
41
42
    if x_type is float:
43
        return struct.unpack('>d', struct.pack('>Q', b | a | d | c | f | e | h | g))[0]
44
    else:
45
        return b | a | d | c | f | e | h | g
46