Python如何推断出在二进制中使用的位数量?

发布于 2025-02-03 18:43:12 字数 755 浏览 6 评论 0 原文

我将其从C转换为Python:

int_fast16_t x;
int_fast16_t y = compute_value();
x = ~y;
y = x+1;

我认为不会

y = compute_value()
y = (~y) + 1

有效:在不应该完成二进制的几位上,它怎么知道? (8?16?32?)。

对于C,它可以使用类型 int_fast16_t 进行明确说明,但是使用Python,我们不知道有很多位。

您如何在Python中这样做?

我读过 python?但是这里更具体: python如何推断出在二进制中使用的位数?

示例:

python如何知道二进制于 3 < 3 << /code>( 0B11 )应在4位上完成: 0b00 或8位: 0B11111100 或16位: 0B1111111111111100

I'm translating this from C to Python:

int_fast16_t x;
int_fast16_t y = compute_value();
x = ~y;
y = x+1;

I don't think

y = compute_value()
y = (~y) + 1

will work: how would it know on how many bits should the binary NOT be done? (8? 16? 32?).

In the case of C, it is explicit with the type int_fast16_t, but with Python we don't know a number of bits in advance.

How do you do this in Python?

I have read How do I do a bitwise Not operation in Python? but here it's more specific: how does Python infer the number of bits to use in a binary NOT?

Example:

How does Python know if the binary NOT of 3 (0b11) should be done on 4 bits: 0b00 or on 8 bits: 0b11111100 or on 16 bits: 0b1111111111111100?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半山落雨半山空 2025-02-10 18:43:12

Python int 具有无限数量的位。将它们倒置的唯一方法是消除数字的迹象。因此,例如 〜1 -2 。要在结果中获取特定数量的位,您必须掩盖这些位。 (〜1)&amp; 0xffff 0xfffe ,这是一点点,我假设由于两个人的补充。

Python int has an infinite number of bits. The only way to invert them all is to negate the sign of the number. So for example ~1 is -2. To get a specific number of bits in the result, you have to mask off those bits. (~1)&0xffff is 0xfffe which is one bit off, I assume due to two's complement.

画离情绘悲伤 2025-02-10 18:43:12

Python如何推断出在二进制中使用的位数?

它在其对操作数具有的二进制表示中使用所有位。 python整数由一个或多个 long s组成(请参阅)。

python如何知道应在4位或8位的二进制(0b11)进行3(0b11):0b1111100或16位:0B11111111111111100?

在没有情况下只有4或8位。它是在上在整数中拥有的64位中的所有在(如果原始值都需要更长的单词)中完成的。

how does Python infer the number of bits to use in a binary NOT?

It uses all bits in the binary representation it has for the operand. Python integers consist of one or more longs (see Python integer objects).

How does Python know if the binary NOT of 3 (0b11) should be done on 4 bits: 0b00 or on 8 bits: 0b11111100 or on 16 bits: 0b1111111111111100?

There is no case where it would be just 4 or 8 bits. It is done on all bits in the 64 bits it has for the integer (or a multiple of that, if the original value needed more long words).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文