简体   繁体   English

在python中将32位解释为Integer

[英]Interpret 32 bits as Integer in python

I read bits from a file. 我从文件中读取位。 The first value is 第一个值是

bits = str(11101111010110011000000000000001)

This is the binary representation of a signed 32 bit integer so this is already in two's complement and little endian. 这是带符号的32位整数的二进制表示,因此它已经是二进制补码和小尾数。 I think the value I want to get is 我认为我想要的价值是

-279347199 -279347199

atleast this website converts it as such http://www.binaryconvert.com/result_signed_int.html?hexadecimal=EF598001 至少这个网站将其转换为http://www.binaryconvert.com/result_signed_int.html?hexadecimal=EF598001

everything I found that solves this problem interprets the bits as pure binary without two's complement and little endian 我发现解决这个问题的一切都将这些位解释为纯二进制,没有二进制补码和小端

A neat trick to convert from two's complement is to find 1 from the end and replace rest of the bits by their complement. 从两个补码转换的巧妙技巧是从末尾找到1并用其补码替换其余的位。

def convert_from_twosc(bits):
    bits = bits[::-1]
    for bit in bits:
        if bit == '1':
            for new_bit in range(bits.index(bit) + 1, len(bits)):
                if bits[new_bit] == '0':
                    bits[new_bit] = '1'
                else:
                    bits[new_bit] = '0'
            break
    return "".join(map(str, bits[::-1]))
bits = input()
number = int(convert_from_twosc(list(bits)) , 2) * -1
print(number)

Output: 输出:

11101111010110011000000000000001
-279347199

This function always assumes input to it, is a signed negative number so be careful. 此函数始终假定输入,是带符号的负数,因此请小心。

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

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