qml.math.int_to_binary¶
- int_to_binary(integer, width)[source]¶
Convert an integer or an array of integers to an array of bitstrings of given length, representing the integers as binaries.
- Parameters:
integer (int | np.ndarray) – Integer(s) to convert. Either a single integers or an array of integers.
width (int) – Length of the bitstrings to which the integer(s) are converted. Note that the
widthleast significant bits corresponding tointegers % 2**widthare returned, discarding the most significant contributions ifinteger > 2**(width-1)-1.
- Returns:
Array of bitstrings representing the
integerinput. Ifintegeris anint, the returned array has shape(width,). Ifintegeris an array of shapeS, the returned array has shape(*S, width).- Return type:
np.ndarray
Example
We may compute the binary representation of the integer
13on five bits, for example:>>> width = 5 >>> print(qml.math.int_to_binary(13, width=width)) [0 1 1 0 1]
This matches the output of
np.binary_reprbut returns a numerical array instead of a string:>>> print(np.binary_repr(13, width=width)) 01101
For an array-typed input, we obtain a new array with an additional axis in the last position, of size
width:>>> x = np.array([[7, 3], [17, 9], [2, 8]]) >>> print(x.shape) (3, 2) >>> bits = qml.math.int_to_binary(x, width=width) >>> print(bits.shape) (3, 2, 5)
The input
integercan be reconstructed from the bit strings via>>> powers_of_two = 2**np.arange(width-1, -1, -1) >>> reconstruction = bits @ powers_of_two >>> print(reconstruction) [[ 7 3] [17 9] [ 2 8]]