Converting signed binary string in two's complement to int?

前端 未结 1 1775
悲哀的现实
悲哀的现实 2021-01-16 11:16

I have a binary string as follows:

String bin = \"1101\";

and I want my int\'s value to be -3 instead of 13

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-16 11:50

    Use if (i >= k) i -= 2 * k; Where k is the smallest positive number your scheme cannot represent. (8 in this case, because 0111 is 7 and 1000 would be negative.)

    13 is greater than 8, so you'd subtract 16 from 13, giving -3.

    0 讨论(0)
提交回复
热议问题