Coverage for tsfpga/math_utils.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-04-15 20:51 +0000

1# -------------------------------------------------------------------------------------------------- 

2# Copyright (c) Lukas Vik. All rights reserved. 

3# 

4# This file is part of the tsfpga project, a project platform for modern FPGA development. 

5# https://tsfpga.com 

6# https://github.com/tsfpga/tsfpga 

7# -------------------------------------------------------------------------------------------------- 

8 

9 

10def to_binary_string(int_value: int, result_width: int) -> str: 

11 """ 

12 Convert natural integer value to a string of 1's and 0's. 

13 Most significant bit is the first (left-most) character in the string. 

14 

15 Arguments: 

16 int_value: The value to be converted. 

17 result_width: The number of bits in the result. The supplied ``int_value`` must fit. 

18 

19 Return: 

20 A string of length ``result_width`` containing only "1" and "0". 

21 """ 

22 if int_value < 0: 

23 raise ValueError(f"Negative value {int_value} not supported") 

24 

25 # bin() returns e.g. "0b10101010" 

26 binary_string = bin(int_value)[2:] 

27 if len(binary_string) > result_width: 

28 raise ValueError(f"Value {int_value} does not fit in {result_width} bits") 

29 

30 # Pad with zeros to the full length 

31 formatting_string = f"{{:0>{result_width}}}" 

32 padded_binary_string = formatting_string.format(binary_string) 

33 assert len(padded_binary_string) == result_width 

34 

35 return padded_binary_string