简体   繁体   English

如何在二进制级别上将 integer 解释为 python 中的不同类型

[英]How can I interpet an integer as a different type in python on a binary level

I want to do the following:我想做以下事情:

a = 4
b = 7

result = int([a, b]) # Result is 1031 or 1796 depending on the endianness

So essentially lay out two unsigned integers next to each other, as one byte, and interpret the region as a two-byte unsigned integer.因此,基本上将两个无符号整数彼此相邻布置为一个字节,并将该区域解释为一个两字节无符号 integer。

Is this possible given python's generic int ?鉴于python的通用int这可能吗?

You have to use bitwise operations: a << 8 | b您必须使用按位运算: a << 8 | b a << 8 | b

Explanation:解释:

First, a << 8 is evaluated.首先,评估a << 8 It's a left shift, so all the bits are going 8 places to the left:这是一个左移,所以所有位都向左移动 8 位:

0000 0000 0000 0100
          ↙↙↙ ↙↙↙
        ↙↙↙ ↙↙↙
      ↙↙↙ ↙↙↙
   ↙↙↙ ↙↙↙
↙↙↙ ↙↙↙
0000 0100 0000 0000

Then the |然后| operator (bitwise or) is evaluated.运算符(按位或)被评估。

   0000 0100 0000 0000  #<= a<<8
OR 0000 0000 0000 0111  #<= b
----------------------
=  0000 0100 0000 0111  #<= a<<8 | b, decimal 1031
======================

The result of the bitwise OR ist an 1 wherever at least one operand has an 1 at this place.只要至少一个操作数在此位置为1 ,按位或的结果就是1 Here it's used to "merge" the two numbers together.在这里,它用于将两个数字“合并”在一起。 Because the left byte of b is all 0 it doesn't affect the left byte of the first operand and vice versa.因为b的左字节全为0 ,所以它不会影响第一个操作数的左字节,反之亦然。

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

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