Python中的二进制补码?

Two#39;s Complement Binary in Python?(Python中的二进制补码?)
本文介绍了Python中的二进制补码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

Python 中的整数存储在二进制补码中,对吗?

Integers in Python are stored in two's complement, correct?

虽然:

>>> x = 5
>>> bin(x)
0b101

还有:

>>> x = -5
>>> bin(x)
-0b101

这很蹩脚.如何让 python 给我 REAL 二进制位的数字,并且前面没有 0b?所以:

That's pretty lame. How do I get python to give me the numbers in REAL binary bits, and without the 0b infront of it? So:

>>> x = 5
>>> bin(x)
0101
>>> y = -5
>>> bin(y)
1011

推荐答案

不确定如何使用标准库获得所需的内容.有一些脚本和包可以为您进行转换.

Not sure how to get what you want using the standard lib. There are a handful of scripts and packages out there that will do the conversion for you.

我只是想说明为什么",以及为什么它不蹩脚.

I just wanted to note the "why" , and why it's not lame.

bin() 不返回二进制位.它将数字转换为二进制字符串.根据 python 语言定义,前导 '0b' 告诉解释器您正在处理二进制数.这样你就可以直接使用二进制数,就像这样

bin() doesn't return binary bits. it converts the number to a binary string. the leading '0b' tells the interpreter that you're dealing with a binary number , as per the python language definition. this way you can directly work with binary numbers, like this

>>> 0b01
1
>>> 0b10
2
>>> 0b11
3
>>> 0b01 + 0b10
3

这不是蹩脚的.太好了.

that's not lame. that's great.

http://docs.python.org/library/functions.html#bin

bin(x)

将整数转换为二进制字符串.

Convert an integer number to a binary string.

http://docs.python.org/reference/lexical_analysis.html#integers

整数和长整数文字由以下词法定义描述:

Integer and long integer literals are described by the following lexical definitions:

bininteger ::= "0" ("b" | "B") bindigit+

bininteger ::= "0" ("b" | "B") bindigit+

bindigit ::= "0" |1"

bindigit ::= "0" | "1"

这篇关于Python中的二进制补码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to find element by part of its id name in selenium with python(如何使用python在selenium中通过其id名称的一部分查找元素)
NoSuchElementException: Message: Unable to locate element while trying to click on the button VISA through Selenium and Python(NoSuchElementException:消息:尝试通过 Selenium 和 Python 单击 VISA 按钮时无法找到元素) - IT屋-程序员软件开发技术分
Selenium not able to click on Get Data button on using Python(Selenium 在使用 Python 时无法单击“获取数据按钮)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python(selenium.common.exceptions.ElementClickInterceptedException:消息:元素点击被拦截:元素不可点击
Selenium Compound class names not permitted(不允许使用硒化合物类名称)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium(selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:尝试使用 selenium 单