将位串转换为32位有符号整数会产生错误的结果 [英] Converting bitstring to 32-bit signed integer yields wrong result
问题描述
我正在尝试解决此网站上的挑战.除了我无法正确地将位字符串转换为其32位带符号整数表示形式之外,我的所有设置都是正确的.
I am trying to solve a challenge on this site. I have everything correct except I can't properly convert a bitstring to its 32-bit signed integer representation.
例如,我有这个位串:
block = '10101010001000101110101000101110'
我自己将此位串转换为32位带符号整数的方式:我从学校中部分记得第一位是符号位.如果为1,则我们为负数,反之亦然.
My own way of converting this bitstring to 32-bit signed integer: I partially remember from school that first bit is the sign bit. If it is 1 we have negative number and vice versa.
当我这样做时,它给我以10为底的数字.它只是将其转换为10以底的数字:
when I do this, it gives me the number in base 10. It just converts it to base 10:
int(block, 2) #yields 2854414894
我尝试排除第一位并转换剩余的31个长度的位串,之后检查了第一位以确定这是否为负数:
I have tried excluding the first bit and convert remaining 31 length bitstring, after that checked the first bit to decide whether this is negative number or not:
int(block[1:32], 2) #yields 706931246
但是正确的答案是 -1440552402
.我应该对该位串执行什么操作才能获得该整数?系统的字节顺序是小字节序还是大字节序是否相关?我的系统是小端的.
But the correct answer is -1440552402
. What operation should I do to this bitstring to get this integer? Is it relevant if the byte order of the system is little endian or big endian? My system is little endian.
推荐答案
您是对的,即高位决定符号,但这不是一个简单的标志.取而代之的是,负数的整个字符都是相反的.这是一个正数1(8位):
You're right that the upper bit determines sign, but it's not a simple flag. Instead, the whole character of negative numbers is inverted. This is a positive number 1 (in 8 bits):
00000001
这是负数1:
11111111
结果是加法和减法环绕".所以4-1是:
The upshot is that addition and subtraction "wrap around". So 4 - 1 would be:
0100 - 0001 = 0011
因此0-1与1_0000_0000-1相同.借位"刚好超出整数的顶部.
And so 0 - 1 is the same as 1_0000_0000 - 1. The "borrow" just goes off the top of the integer.
取反"数字的一般方法是取反,加1".这是双向的,所以您可以从正数转为负数,然后返回.
The general way to "negate" a number is "invert the bits, add 1". This works both ways, so you can go from positive to negative and back.
在您的情况下,请使用前导'1'检测是否需要取反,然后转换为int,然后执行取反步骤.不过请注意,由于python的 int
不是固定宽度值,因此存在一个单独的内部标志(Python int
并非"32位"数字,它是一个任意精度的整数,其动态分配的表示形式以简单的2的补码之外的其他方式存储.)
In your case, use the leading '1' to detect whether negation is needed, then convert to int, then maybe perform the negation steps. Note, however, that because python's int
is not a fixed-width value, there's a separate internal flag (a Python int
is not a "32-bit" number, it's an arbitrary-precision integer, with a dynamically allocated representation stored in some fashion other than simple 2's complement).
block = '10101010001000101110101000101110'
asnum = int(block, 2)
if block[0] == '1':
asnum ^= 0xFFFFFFFF
asnum += 1
asnum = -asnum
print(asnum)
这篇关于将位串转换为32位有符号整数会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!