def twos_compliment(byte_arr): a = byte_arr[0]; b = byte_arr[1]; c = byte_arr[2] out = ((a<<16)&0xff0000) | ((b<<8)&0xff00) | (c&0xff) neg = (a & (1<<7) != 0) # first bit of a is the "signed bit." if it's a 1, then the value is negative if neg: out -= (1 << 24) print hex(a), hex(b), hex(c), neg, out return out # 1234567 twos_compliment([0b00010010, 0b11010110, 0b10000111]) # -1234567 twos_compliment([0b11101101, 0b00101001, 0b01111001]) # 7654321 twos_compliment([0b01110100, 0b11001011, 0b10110001]) # -7654321 twos_compliment([0b10001011, 0b00110100, 0b01001111])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question