Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two's Complement in Python

Is there a built in function in python which will convert a binary string, for example '111111111111', to the two's complement integer -1?

like image 667
Jim Avatar asked Oct 22 '09 00:10

Jim


People also ask

How do you calculate 2's complement?

To get 2's complement of binary number is 1's complement of given number plus 1 to the least significant bit (LSB). For example 2's complement of binary number 10010 is (01101) + 1 = 01110.

What is 2's complement with example?

For example, 2's complement of “01000” is “11000” (Note that we first find one's complement of 01000 as 10111). If there are all 1's (in one's complement), we add an extra 1 in the string. For example, 2's complement of “000” is “1000” (1's complement of “000” is “111”).


1 Answers

Two's complement subtracts off (1<<bits) if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.

A function for two's complement of an int...

def twos_comp(val, bits):     """compute the 2's complement of int value val"""     if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255         val = val - (1 << bits)        # compute negative value     return val                         # return positive value as is 

Going from a binary string is particularly easy...

binary_string = '1111' # or whatever... no '0b' prefix out = twos_comp(int(binary_string,2), len(binary_string)) 

A bit more useful to me is going from hex values (32 bits in this example)...

hex_string = '0xFFFFFFFF' # or whatever... '0x' prefix doesn't matter out = twos_comp(int(hex_string,16), 32) 
like image 153
travc Avatar answered Oct 09 '22 17:10

travc