What is numpy.binary_repr() in Python?

Overview

The numpy.binary_repr() method generates a binary representation of argument numbers (which can either be a negative or positive value) as a string.

A negative number means that if the passed argument is negative, the function will take its complement. Now, the question arises of whether it will tackle negative values as an argument. If we set the width argument, it will simply compute two's complement of that number and return it as a string. Otherwise, it will append a negative sign at the end of the absolute value.

You can learn more about two's complement by clicking here.

Syntax


numpy.binary_repr(num, width=None)

Parameters

It takes the following argument values.

  • num: Integer decimal numbers.
  • width: Default= None, it provides the length of output string in case of negative numbers when two's complement is computed.

Return value

bin: It returns a string that shows binary representation on a decimal integer value.

Explanation

The code snippet below represents different use cases. For instance, the argument value can either be a negative number or a number with variable width.

import numpy as np
# argument a positive integer value
print(np.binary_repr(3))
# argument a negative integer value
print(np.binary_repr(-3))
# passing positive value with width=4
print(np.binary_repr(3, width=4))
# passing negative number with width=3
print(np.binary_repr(-3, width=3))
# passing negative number with width=5
print(np.binary_repr(-3, width=5))

    Free Resources