简体   繁体   English

为什么此python正确输出16位2s补码?

[英]Why does this python correctly output the 16 bit 2s complement?

Let binStr be an integer array, and number be the integer to "translate" to binary. 设binStr为整数数组,数字为要“翻译”为二进制的整数。

count = len(binStr) - 1
while count >= 0:
      binStr[count] = 0 if number%2 == 0 else 1
      number //= 2
      count -= 1

I wrote this while fiddling around and noticed it works for both signs. 我在摆弄时写了这个,发现它对两个标志都适用。 Why does this work for both negative and positive numbers? 为什么这对负数和正数都有效? It should yield the same bits for negative and positive, but it actually works correctly and does not. 对于负数和正数,它应产生相同的位,但实际上它正常工作,而不能正常工作。 Why? 为什么?

whoops i misread the question initially... 哎呀,我最初看错了这个问题...

yeah the core issue is that floor division works differently for positive and negative numbers, as noted above by Ryan 是的,核心问题是,底数划分对正数和负数的作用不同,正如瑞安(Ryan)所指出的那样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM