Is there a way to obtain the binary representation of a number in Python? It has to be able to represent negative numbers as well. I already tried the function from numpy np.binary_repr(Decimal(-1))
but it results in an error. To be precise - I want to somehow obtain the binary representations of fixed point numbers (positive and negative), so I can put them into Verilog code.
Let's say I have the number 1,5
in decimal. I want to write it with two bit precision and three integer bits and a sign. In binary this would be 0001,10
, so basically 000110
. I could do this easily by hand, but the problem is that I also have negative ones and furthermore they don't have a finite expansion after the point (like 1/3
in decimal)
To be more precise: If I have a number like -1.5
in decimal a sign, fraction precision of two, and integer precision of two, I expect the number 110,10
to be the output - the first digit is the sign, the next two the number, the next two are the fraction.