Two's Complement Binary in Python?
Not sure how to get what you want using the standard lib. There are a handful of scripts and packages out there that will do the conversion for you.
I just wanted to note the "why" , and why it's not lame.
bin() doesn't return binary bits. it converts the number to a binary string. the leading '0b' tells the interpreter that you're dealing with a binary number , as per the python language definition. this way you can directly work with binary numbers, like this
>>> 0b01
1
>>> 0b10
2
>>> 0b11
3
>>> 0b01 + 0b10
3
that's not lame. that's great.
http://docs.python.org/library/functions.html#bin
bin(x)
Convert an integer number to a binary string.
http://docs.python.org/reference/lexical_analysis.html#integers
Integer and long integer literals are described by the following lexical definitions:
bininteger ::= "0" ("b" | "B") bindigit+
bindigit ::= "0" | "1"
Python - Most effective way to implement two's complement?
x=int(a,2)
num_bits = 10
print x - (1 << num_bits)
I think this should solve the problem
Two's Complement algorithm in Python
Use this simple function
def twos_comp(val):
return 0b111111111111 - val # 12 ones
You may test it with
val = 0b111100001111
print("{:012b}".format(twos_comp(val)))
and you will got
000011110000
If it is not what you wanted, use this function instead
def twos_comp(val):
return 0b1000000000000 - val # 1 with 12 zeroes
How to convert to and from two's complement and sign & magnitude?
You can only perform this kind of conversion on an integer with a fixed number of bits. I've made it a parameter to the function.
The two operations are complementary, you can use the same function to go both directions. You separate the sign bit, then complement the remainder and combine them back together.
def twos_comp_to_sign_mag(value, bits=8):
sign_bit = 1 << (bits - 1)
sign = value & sign_bit
mask = sign_bit - 1
if sign:
value = -(value & mask)
return (sign_bit & value) | (value & mask)
>>> twos_comp_to_sign_mag(255)
129
>>> twos_comp_to_sign_mag(129)
255
two's complement of numbers in python
If you're doing something like
format(num, '016b')
to convert your numbers to a two's complement string representation, you'll want to actually take the two's complement of a negative number before stringifying it:
format(num if num >= 0 else (1 << 16) + num, '016b')
or take it mod 65536
:
format(num % (1 << 16), '016b')
bitwise operation and Two's complement in python
You have to write your own implementation of the arithmetic right shift of a 16-bit value, if this is what you need. I suggest you this one, very easy to understand:
def arithmetic_right_shift_on_16_bits(val, n):
# Get the sign bit
s = val & 0x8000
# Perform the shifts, padding with the sign bit
for _ in range(n):
val >>= 1
val |= s
return val
a = arithmetic_right_shift_on_16_bits(0b0000000011111111, 4)
print(bin(a)) # 0b1111
b = arithmetic_right_shift_on_16_bits(0b1000000011111111, 4)
print(bin(b)) # 0b1111100000001111
Converting an integer to signed 2's complement binary string
Nothing built in, but this is more concise:
def f(n):
nbits = n.bit_length() + 1
return f"{n & ((1 << nbits) - 1):0{nbits}b}"
Then, e.g.,
>>> f(0)
'0'
>>> f(1)
'01'
>>> f(2)
'010'
>>> f(3)
'011'
>>> f(-1)
'11'
>>> f(-2)
'110'
>>> f(-3)
'101'
Related Topics
Python VS. Ruby for Metaprogramming
Is There a Python Equivalent for Rspec to Do Tdd
The Simplest Possible Reverse Proxy
Which of These Scripting Languages Is More Appropriate for Pen-Testing
Simple File Server to Serve Current Directory
Python: What's the Difference Between Pythonbrew and Virtualenv
Is There Something Like Bpython for Ruby
Python, Ruby, Haskell - Do They Provide True Multithreading
Scripting Http More Effeciently
Learning Ruby from Python; Differences and Similarities
Please Introduce a Multi-Processing Library in Perl or Ruby
If Monkey Patching Is Permitted in Both Ruby and Python, Why Is It More Controversial in Ruby
Looking for Recommendation on How to Convert PDF into Structured Format
Does Ruby Have Something Like Python's List Comprehensions
Programmatically Extract Data from an Excel Spreadsheet
In Python Can One Implement Mixin Behavior Without Using Inheritance