forked from mzahana/siyi_sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
39 lines (34 loc) · 865 Bytes
/
utils.py
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
"""
Some useful functions to manipulate bytes
Author: Mohamed Abdelkader
Contact: [email protected]
"""
def toHex(intval, nbits):
"""
Converts an integer to hexdecimal.
Useful for negative integers where hex() doesn't work as expected
Params
--
intaval: [int] Integer number
nbits: [int] Number of bits
Returns
--
String of the hexdecimal value
"""
h = format((intval + (1 << nbits)) % (1 << nbits),'x')
if len(h)==1:
h="0"+h
return h
def toInt(hexval):
"""
Converts hexidecimal value to an integer number, which can be negative
Ref: https://www.delftstack.com/howto/python/python-hex-to-int/
Params
--
hexval: [string] String of the hex value
"""
bits = 16
val = int(hexval, bits)
if val & (1 << (bits-1)):
val -= 1 << bits
return val