diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 9c1f596..ae3b608 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -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: diff --git a/src/pyubx2/ubxhelpers.py b/src/pyubx2/ubxhelpers.py index 2d42c61..72b6830 100644 --- a/src/pyubx2/ubxhelpers.py +++ b/src/pyubx2/ubxhelpers.py @@ -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)) diff --git a/tests/test_static.py b/tests/test_static.py index 60664f2..4629597 100644 --- a/tests/test_static.py +++ b/tests/test_static.py @@ -40,6 +40,8 @@ utc2itow, val2bytes, val2sphp, + val2twoscomp, + val2signmag, ) @@ -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']