Coverage for /home/runner/work/zserio/zserio/compiler/extensions/python/runtime/src/zserio/bitposition.py: 100%

13 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2024-12-05 10:43 +0000

1""" 

2The module provides help methods for bit position calculation. 

3""" 

4 

5from zserio.exception import PythonRuntimeException 

6 

7 

8def alignto(alignment_value: int, bitposition: int) -> int: 

9 """ 

10 Aligns the bit size to the given alignment value. 

11 

12 :param alignment_value: Value to align. 

13 :param bitposition: Current bit position where to apply alignment. 

14 :returns: Aligned bit position. 

15 """ 

16 

17 if bitposition <= 0 or alignment_value == 0: 

18 return bitposition 

19 

20 return (((bitposition - 1) // alignment_value) + 1) * alignment_value 

21 

22 

23def bits_to_bytes(numbits: int) -> int: 

24 """ 

25 Converts number of bits to bytes. 

26 

27 :param numbits: The number of bits to convert. 

28 :returns: Number of bytes 

29 :raises PythonRuntimeException: If number of bits to convert is not divisible by 8. 

30 """ 

31 

32 if numbits % 8 != 0: 

33 raise PythonRuntimeException(f"bitposition: '{numbits}' is not a multiple of 8!") 

34 

35 return numbits // 8 

36 

37 

38def bytes_to_bits(num_bytes: int) -> int: 

39 """ 

40 Converts number of bytes to bits. 

41 

42 :param num_bytes: The n number of bytes to convert. 

43 :returns: Number of bits. 

44 """ 

45 

46 return num_bytes * 8 

47 

48 

49def bitsize_to_bytesize(bitsize: int) -> int: 

50 """ 

51 Converts number of bits to number of bytes. 

52 

53 :param bitsize: Size in bits to convert. 

54 :returns: Size in bytes. 

55 """ 

56 

57 return (bitsize + 7) // 8