将python整数转换为其带符号的二进制表示

时间:2015-09-04 13:39:30

标签: python binary integer twos-complement

给定一个正整数,例如171和“寄存器”大小,例如8。

我想要由二进制表示形式171表示的整数,即'0b10101011'被解释为二进制补码。

在本案中,171应为-85。 它是负的,因为给定“寄存器”大小为8,MSB为1。

我希望我设法解释我的问题。 我该如何进行转换?

我尝试了什么:

<?php

function getOS($userAgent) {

$osPlatform    =   "Unknown OS Platform";

$os_array       =   array(
    'windows nt 10.0'    => 'Windows 10',
    'windows nt 6.2'     =>  'Windows 8',
    'windows nt 6.1'     =>  'Windows 7',
    'windows nt 6.0'     =>  'Windows Vista',
    'windows nt 5.2'     =>  'Windows Server 2003/XP x64',
    'windows nt 5.1'     =>  'Windows XP',
    'windows xp'         =>  'Windows XP',
    'windows nt 5.0'     =>  'Windows 2000',
    'windows me'         =>  'Windows ME',
    'win98'              =>  'Windows 98',
    'win95'              =>  'Windows 95',
    'win16'              =>  'Windows 3.11',
    'macintosh|mac os x' =>  'Mac OS X',
    'mac_powerpc'        =>  'Mac OS 9',
    'linux'              =>  'Linux',
    'ubuntu'             =>  'Ubuntu',
    'phone'             =>  'iPhone',
    'pod'               =>  'iPod',
    'pad'               =>  'iPad',
    'android'            =>  'Android',
    'blackberry'         =>  'BlackBerry',
    'webos'              =>  'Mobile'
);

foreach ($os_array as $label => $value) {
    if (stripos($userAgent, $label)) {
        return $value;
    }
}

return $osPlatform;

}

function getBrowser($userAgent) {

$browser        =   "Unknown Browser";

$browser_array  =   array(
    'msie'       =>  'Internet Explorer',
    'firefox'    =>  'Firefox',
    'safari'     =>  'Safari',
    'chrome'     =>  'Chrome',
    'opera'      =>  'Opera',
    'netscape'   =>  'Netscape',
    'maxthon'    =>  'Maxthon',
    'konqueror'  =>  'Konqueror',
    'mobile'     =>  'Handheld Browser'
);

foreach ($browser_array as $label => $value) {
    if (stripos($userAgent, $label)) {
        return $value;
    }
}

return $browser;

}

$userAgent     =   $_SERVER['HTTP_USER_AGENT'];
//$userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36      (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36';


$user_os        =   getOS($userAgent);
$user_browser   =   getBrowser($userAgent);

$device_details =   "<strong>Browser: </strong>".$user_browser."<br />                    <strong>Operating System: </strong>".$user_os."";

print_r($device_details);

//echo("<br /><br /><br />".$_SERVER['HTTP_USER_AGENT']."");

2 个答案:

答案 0 :(得分:3)

您不需要二进制转换来实现这一目标:

>>> size = 8
>>> value = 171
>>> unsigned = value % 2**size 
>>> signed = unsigned - 2**size if unsigned >= 2**(size-1) else unsigned
>>> signed
-85

答案 1 :(得分:2)

可能有一百种不同的方法可以做到这一点。这是一对夫妇。

如果大小是8的倍数,那么这样的事情将起作用:

x = int.from_bytes(value.to_bytes(size // 8, byteorder='big'), byteorder='big', signed=True)

如果大小不是8的倍数,那么你可以这样做:

mask = 1 << (size - 1)
x = (value ^ mask) - mask

两者都假设该值太大而无法放入&#34;寄存器&#34;。