Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

What is numpy.binary_repr() in Python?

AKASH BAJWA

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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))
Obtaining the binary representation

    RELATED TAGS

    communitycreator
    python

    Grokking Modern System Design Interview for Engineers & Managers

    Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

    Answers Code
    Keep Exploring