Coverage for tsfpga/math_utils.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v6.4, created at 2022-05-28 04:01 +0000

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

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

3# 

4# This file is part of the tsfpga project. 

5# https://tsfpga.com 

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

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

8 

9 

10def to_binary_string(int_value, result_width): 

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 (int): The value to be converted. 

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

18 

19 Returns: 

20 str: 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