Skip to content

Commit

Permalink
add val2twoscomp val2signmag helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
semuadmin committed Nov 7, 2024
1 parent 806f77f commit ac05f6d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
2 changes: 2 additions & 0 deletions RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

ENHANCEMENTS:

1. Add helper methods `val2twoscomp` and `val2signmag` to convert signed integer to appropriate two's complement or sign magnitude binary representation.

### RELEASE 1.2.47

ENHANCEMENTS:
Expand Down
28 changes: 28 additions & 0 deletions src/pyubx2/ubxhelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -622,3 +622,31 @@ def process_monver(msg: object) -> dict:
verdata["gnss"] = gnss_supported

return verdata


def val2twoscomp(val: int, att: str) -> int:
"""
Convert signed integer to two's complement binary representation.
:param int val: value
:param str att: attribute type e.g. "U024"
:return: two's complement representation of value
:rtype: int
"""

return val & pow(2, attsiz(att)) - 1


def val2signmag(val: int, att: str) -> int:
"""
Convert signed integer to sign magnitude binary representation.
High-order bit represents sign (0 +ve, 1 -ve).
:param int val: value
:param str att: attribute type e.g. "U024"
:return: sign magnitude representation of value
:rtype: int
"""

return (abs(val) & pow(2, attsiz(att)) - 1) | ((1 if val < 0 else 0) << attsiz(att))
14 changes: 14 additions & 0 deletions tests/test_static.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
utc2itow,
val2bytes,
val2sphp,
val2twoscomp,
val2signmag,
)


Expand Down Expand Up @@ -333,6 +335,18 @@ def testprocess_monver(self):
res = process_monver(msg)
self.assertEqual(res, EXPECTED_RESULT)

def testval2twoscomp(self):
res = val2twoscomp(10, "U24")
self.assertEqual(res, 0b0000000000000000000001010)
res = val2twoscomp(-10, "U24")
self.assertEqual(res, 0b111111111111111111110110)

def testval2signmag(self):
res = val2signmag(10, "U24")
self.assertEqual(res, 0b0000000000000000000001010)
res = val2signmag(-10, "U24")
self.assertEqual(res, 0b1000000000000000000001010)


if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
Expand Down

0 comments on commit ac05f6d

Please sign in to comment.