How can I get the integer bit sign in python?

I want to have access to the bit sign of a number in python. I can do something like n >> 31in C since an int is represented as 32 bits.

I cannot use the conditional operator and> <.

+6
source share
2 answers

in python 3, integers are not fixed in size and are not represented using the internal representation of the CPU (which allows very large numbers to be processed without problems).

So the best way is

signbit = 1 if n < 0 else 0

or

signbit = int(n < 0)

EDIT: < > ( , ), , a-b , a , b,

abs(a-b) == a-b

< > ( , , abs , )

+5

, Python . , int - . . bin(-3) "" : '-0b11'

, . , .

def sign(a):
    try:
        return (1 - int(a / (a**2)**0.5)) // 2
    except ZeroDivisionError:
        return 0

def return_bigger(a, b):
    s = sign(b - a)
    return a * s + b * (1 - s)


assert sign(-33) == 1
assert sign(33) == 0    

assert return_bigger(10, 15) == 15
assert return_bigger(25, 3) == 25
assert return_bigger(42, 42) == 42
  • (a**2)**0.5 abs, , .
  • try/except , 0 ( ).
  • , , , - - , .
+1

All Articles