优秀的编程知识分享平台

网站首页 > 技术文章 正文

Python位函数(bit_length,to_bytes和from_bytes)

nanyue 2024-11-20 19:35:02 技术文章 6 ℃

int类型实现了numbers.Integral抽象基类。

1. int.bit_length()

返回表示二进制整数(不包括符号和前导零)的位数。

演示代码

num = 7
print(num.bit_length()) 
  
num = -7
print(num.bit_length()) 

输出

3
3

2. int.to_bytes(length, byteorder, *, signed=False)

返回表示整数的字节数组。

# Returns byte representation of 1024 in a 
# big endian machine. 
print((1024).to_bytes(2, byteorder ='big')) 

输出:

b'\x04\x00'

3. int.from_bytes(bytes, byteorder, *, signed=False)

返回由给定的字节数组表示的整数。

# Returns integer value of '\x00\x10' in big endian machine. 
print(int.from_bytes(b'\x00\x10', byteorder ='big')) 

输出:

16

Tags:

最近发表
标签列表