Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

two's complement of numbers in python

I am writing code that will have negative and positive numbers all 16 bits long with the MSB being the sign aka two's complement. This means the smallest number I can have is -32768 which is 1000 0000 0000 0000 in two's complement form. The largest number I can have is 32767 which is 0111 1111 1111 1111.

The issue I am having is python is representing the negative numbers with the same binary notation as positive numbers just putting a minus sign out the front i.e. -16384 is displayed as -0100 0000 0000 0000 what I want to be displayed for a number like -16384 is 1100 0000 0000 0000.

I am not quite sure how this can be coded. This is the code i have. Essentially if the number is between 180 and 359 its going to be negative. I need to display this as a twos compliment value. I dont have any code on how to display it because i really have no idea how to do it.

def calculatebearingActive(i):

    numTracks = trackQty_Active
    bearing = (((i)*360.0)/numTracks)
    if 0< bearing <=179:
        FC = (bearing/360.0)
        FC_scaled = FC/(2**(-16))
        return int(FC_scaled)

    elif 180<= bearing <=359:
        FC = -1*(360-bearing)/(360.0)
        FC_scaled = FC/(2**(-16))
        return int(FC_scaled)

    elif bearing ==360:
        FC = 0
        return FC
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...