将字节转换为int? [英] Convert bytes to int?

查看:112
本文介绍了将字节转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个加密/解密程序,我需要能够将字节转换为整数。我知道:

I'm currently working on an encryption/decryption program and I need to be able to convert bytes to an integer. I know that:

bytes([3]) = b'\x03'

但是我无法找出如何进行逆运算。我在做什么完全错误?

Yet I cannot find out how to do the inverse. What am I doing terribly wrong?

推荐答案

假设您的年龄至少为3.2,则有一个为此内置的

Assuming you're on at least 3.2, there's a built in for this:


int.from_bytes 字节,字节序,*,符号= False

...

参数字节必须是类似字节的对象或可迭代的
产生字节。

The argument bytes must either be a bytes-like object or an iterable producing bytes.

byteorder参数确定用于表示
整数的字节顺序。如果byteorder为 big,则最高有效字节位于字节数组的
开头。如果byteorder是 little,则
个最高有效字节在字节数组的末尾。要请求主机系统的
本机字节顺序,请使用sys.byteorder作为字节
的顺序值。

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

signed参数指示是否为2补码用于
表示整数。

The signed argument indicates whether two’s complement is used to represent the integer.


## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024

这篇关于将字节转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆