PYTHON 之 bytes、str和int之间的一些转换

本文详细介绍了Python中各种数据类型间的转换方法,包括bcd与string、bytes与int、bytes与int数组之间的转换,以及bytes与hex字符串的相互转换。同时,文章还提供了使用Python内置函数进行数据类型转换的具体示例。
部署运行你感兴趣的模型镜像

1、bcd和string的相互转换

import binascii
b = b'\x12\x34'
s = binascii.b2a_hex(b).decode()
#b'\x12\x34'->'1234'
 
s = '1234'
b = binascii.a2b_hex(s)
#'1234'->b'\x124'=b'\x12\x34'

2、bytes和int的相互转换

b = b'\x12\x34'
n = int.from_bytes(b,byteorder='big',signed=False)
#b'\x12\x34'->4660
 
n = 4660
b = n.to_bytes(length=2,byteorder='big',signed=False)
#4660->b'\x12\x34'

3、bytes和int[]的相互转换

b = b'\x12\x34'
n = []
for i in b[:]:
    n.append(i)
#b'\x12\x34'->[12,34]
 
n = [12,34]
b = bytes(n)
#[12,34]->b'\x12\x34'

4 bytes和hex字符串之间的相互转换。

到了python 3.5之后,就可以像下面这么干了:

>>> a = 'aabbccddeeff'
>>> a_bytes = bytes.fromhex(a)
>>> print(a_bytes)
b'\xaa\xbb\xcc\xdd\xee\xff'
>>> aa = a_bytes.hex()
>>> print(aa)
aabbccddeeff
>>>

5 HEX转INT,INT转BYTE, BYTE转字符串

import sys
loginlidar = (0x02, 0x73, 0x4D, 0x4E, 0x20, 0x53, 0x65, 0x74, 0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x4D, 0x6F, 0x64, 0x65, 0x20, 0x30, 0x33, 0x20, 0x46, 0x34, 0x37, 0x32, 0x34, 0x37, 0x34, 0x34, 0x03)
b = bytes(loginlidar)
print(loginlidar)
print(len(b))
print(b.decode())
print(len(b.decode()))

输出:
(2, 115, 77, 78, 32, 83, 101, 116, 65, 99, 99, 101, 115, 115, 77, 111, 100, 101, 32, 48, 51, 32, 70, 52, 55, 50, 52, 55, 52, 52, 3)
31
sMN SetAccessMode 03 F4724744
31

6 BYTES 用法

class bytes(object)
 |  bytes(iterable_of_ints) -> bytes
 |  bytes(string, encoding[, errors]) -> bytes
 |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
 |  bytes(int) -> bytes object of size given by the parameter initialized with null bytes
 |  bytes() -> empty bytes object
 |  
 |  Construct an immutable array of bytes from:
 |    - an iterable yielding integers in range(256)
 |    - a text string encoded using the specified encoding
 |    - any object implementing the buffer API.
 |    - an integer
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  capitalize(...)
 |      B.capitalize() -> copy of B
 |      
 |      Return a copy of B with only its first character capitalized (ASCII)
 |      and the rest lower-cased.
 |  
 |  center(...)
 |      B.center(width[, fillchar]) -> copy of B
 |      
 |      Return B centered in a string of length width.  Padding is
 |      done using the specified fill character (default is a space).
 |  
 |  count(...)
 |      B.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of subsection sub in
 |      bytes B[start:end].  Optional arguments start and end are interpreted
 |      as in slice notation.
 |  
 |  decode(self, /, encoding='utf-8', errors='strict')
 |      Decode the bytes using the codec registered for encoding.
 |      
 |      encoding
 |        The encoding with which to decode the bytes.
 |      errors
 |        The error handling scheme to use for the handling of decoding errors.
 |        The default is 'strict' meaning that decoding errors raise a
 |        UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
 |        as well as any other name registered with codecs.register_error that
 |        can handle UnicodeDecodeErrors.
 |  
 |  endswith(...)
 |      B.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if B ends with the specified suffix, False otherwise.
 |      With optional start, test B beginning at that position.
 |      With optional end, stop comparing B at that position.
 |      suffix can also be a tuple of bytes to try.
 |  
 |  expandtabs(...)
 |      B.expandtabs(tabsize=8) -> copy of B
 |      
 |      Return a copy of B where all tab characters are expanded using spaces.
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      B.find(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in B where subsection sub is found,
 |      such that sub is contained within B[start,end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  hex(...)
 |      B.hex() -> string
 |      
 |      Create a string of hexadecimal numbers from a bytes object.
 |      Example: b'\xb9\x01\xef'.hex() -> 'b901ef'.
 |  
 |  index(...)
 |      B.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in B where subsection sub is found,
 |      such that sub is contained within B[start,end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the subsection is not found.
 |  
 |  isalnum(...)
 |      B.isalnum() -> bool
 |      
 |      Return True if all characters in B are alphanumeric
 |      and there is at least one character in B, False otherwise.
 |  
 |  isalpha(...)
 |      B.isalpha() -> bool
 |      
 |      Return True if all characters in B are alphabetic
 |      and there is at least one character in B, False otherwise.
 |  
 |  isascii(...)
 |      B.isascii() -> bool
 |      
 |      Return True if B is empty or all characters in B are ASCII,
 |      False otherwise.
 |  
 |  isdigit(...)
 |      B.isdigit() -> bool
 |      
 |      Return True if all characters in B are digits
 |      and there is at least one character in B, False otherwise.
 |  
 |  islower(...)
 |      B.islower() -> bool
 |      
 |      Return True if all cased characters in B are lowercase and there is
 |      at least one cased character in B, False otherwise.
 |  
 |  isspace(...)
 |      B.isspace() -> bool
 |      
 |      Return True if all characters in B are whitespace
 |      and there is at least one character in B, False otherwise.
 |  
 |  istitle(...)
 |      B.istitle() -> bool
 |      
 |      Return True if B is a titlecased string and there is at least one
 |      character in B, i.e. uppercase characters may only follow uncased
 |      characters and lowercase characters only cased ones. Return False
 |      otherwise.
 |  
 |  isupper(...)
 |      B.isupper() -> bool
 |      
 |      Return True if all cased characters in B are uppercase and there is
 |      at least one cased character in B, False otherwise.
 |  
 |  join(self, iterable_of_bytes, /)
 |      Concatenate any number of bytes objects.
 |      
 |      The bytes whose method is called is inserted in between each pair.
 |      
 |      The result is returned as a new bytes object.
 |      
 |      Example: b'.'.join([b'ab', b'pq', b'rs']) -> b'ab.pq.rs'.
 |  
 |  ljust(...)
 |      B.ljust(width[, fillchar]) -> copy of B
 |      
 |      Return B left justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space).
 |  
 |  lower(...)
 |      B.lower() -> copy of B
 |      
 |      Return a copy of B with all ASCII characters converted to lowercase.
 |  
 |  lstrip(self, bytes=None, /)
 |      Strip leading bytes contained in the argument.
 |      
 |      If the argument is omitted or None, strip leading  ASCII whitespace.
 |  
 |  partition(self, sep, /)
 |      Partition the bytes into three parts using the given separator.
 |      
 |      This will search for the separator sep in the bytes. If the separator is found,
 |      returns a 3-tuple containing the part before the separator, the separator
 |      itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing the original bytes
 |      object and two empty bytes objects.
 |  
 |  replace(self, old, new, count=-1, /)
 |      Return a copy with all occurrences of substring old replaced by new.
 |      
 |        count
 |          Maximum number of occurrences to replace.
 |          -1 (the default value) means replace all occurrences.
 |      
 |      If the optional argument count is given, only the first count occurrences are
 |      replaced.
 |  
 |  rfind(...)
 |      B.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in B where subsection sub is found,
 |      such that sub is contained within B[start,end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      B.rindex(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in B where subsection sub is found,
 |      such that sub is contained within B[start,end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raise ValueError when the subsection is not found.
 |  
 |  rjust(...)
 |      B.rjust(width[, fillchar]) -> copy of B
 |      
 |      Return B right justified in a string of length width. Padding is
 |      done using the specified fill character (default is a space)
 |  
 |  rpartition(self, sep, /)
 |      Partition the bytes into three parts using the given separator.
 |      
 |      This will search for the separator sep in the bytes, starting at the end. If
 |      the separator is found, returns a 3-tuple containing the part before the
 |      separator, the separator itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing two empty bytes
 |      objects and the original bytes object.
 |  
 |  rsplit(self, /, sep=None, maxsplit=-1)
 |      Return a list of the sections in the bytes, using sep as the delimiter.
 |      
 |        sep
 |          The delimiter according which to split the bytes.
 |          None (the default value) means split on ASCII whitespace characters
 |          (space, tab, return, newline, formfeed, vertical tab).
 |        maxsplit
 |          Maximum number of splits to do.
 |          -1 (the default value) means no limit.
 |      
 |      Splitting is done starting at the end of the bytes and working to the front.
 |  
 |  rstrip(self, bytes=None, /)
 |      Strip trailing bytes contained in the argument.
 |      
 |      If the argument is omitted or None, strip trailing ASCII whitespace.
 |  
 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the sections in the bytes, using sep as the delimiter.
 |      
 |      sep
 |        The delimiter according which to split the bytes.
 |        None (the default value) means split on ASCII whitespace characters
 |        (space, tab, return, newline, formfeed, vertical tab).
 |      maxsplit
 |        Maximum number of splits to do.
 |        -1 (the default value) means no limit.
 |  
 |  splitlines(self, /, keepends=False)
 |      Return a list of the lines in the bytes, breaking at line boundaries.
 |      
 |      Line breaks are not included in the resulting list unless keepends is given and
 |      true.
 |  
 |  startswith(...)
 |      B.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if B starts with the specified prefix, False otherwise.
 |      With optional start, test B beginning at that position.
 |      With optional end, stop comparing B at that position.
 |      prefix can also be a tuple of bytes to try.
 |  
 |  strip(self, bytes=None, /)
 |      Strip leading and trailing bytes contained in the argument.
 |      
 |      If the argument is omitted or None, strip leading and trailing ASCII whitespace.
 |  
 |  swapcase(...)
 |      B.swapcase() -> copy of B
 |      
 |      Return a copy of B with uppercase ASCII characters converted
 |      to lowercase ASCII and vice versa.
 |  
 |  title(...)
 |      B.title() -> copy of B
 |      
 |      Return a titlecased version of B, i.e. ASCII words start with uppercase
 |      characters, all remaining cased characters have lowercase.
 |  
 |  translate(self, table, /, delete=b'')
 |      Return a copy with each character mapped by the given translation table.
 |      
 |        table
 |          Translation table, which must be a bytes object of length 256.
 |      
 |      All characters occurring in the optional argument delete are removed.
 |      The remaining characters are mapped through the given translation table.
 |  
 |  upper(...)
 |      B.upper() -> copy of B
 |      
 |      Return a copy of B with all ASCII characters converted to uppercase.
 |  
 |  zfill(...)
 |      B.zfill(width) -> copy of B
 |      
 |      Pad a numeric string B with zeros on the left, to fill a field
 |      of the specified width.  B is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  fromhex(string, /) from builtins.type
 |      Create a bytes object from a string of hexadecimal numbers.
 |      
 |      Spaces between two numbers are accepted.
 |      Example: bytes.fromhex('B9 01EF') -> b'\\xb9\\x01\\xef'.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  maketrans(frm, to, /)
 |      Return a translation table useable for the bytes or bytearray translate method.
 |      
 |      The returned table will be one where each byte in frm is mapped to the byte at
 |      the same position in to.
 |      
 |      The bytes objects frm and to must be of the same length.

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

<think>我们首先需要将用户的问题化为一个明确的任务:如何将Python中的bytes类型转换int或float等数值类型。 在Python中,我们可以使用int.from_bytes()方法将bytes转换为整数,或者使用struct模块来解析bytes为各种类型(包括intfloat)。 此外,我们也可以使用float()函数,但通常需要先将bytes解码为字符串,然后再转换为浮点数(需要注意编码问题)。 具体方法: 1. bytesint: 对于整数,可以使用int.from_bytes(bytes, byteorder, *, signed=False)方法。 其中,byteorder指定字节序('big'或'little'),signed指示是否有符号。 2. bytesfloat: 通常使用struct模块。例如,如果bytes表示一个IEEE 754标准的浮点数(如4字节的float或8字节的double),我们可以使用struct.unpack()来转换。 3. 如果bytes是表示数字的字符串(如b"123"),则可以先使用bytes.decode()将其解码为字符串,再用int()或float()转换。 下面给出一些示例代码: 示例1:将bytes对象(表示整数)转换int data = b'\x00\x10' # 16 num = int.from_bytes(data, byteorder='big') # 16 示例2:将bytes对象(表示浮点数)转换为float import struct data = b'\x40\x49\x0f\xdb' # 3.1415926535的近似值(单精度浮点数) num = struct.unpack('>f', data)[0] # 使用大端序,'>f'表示大端序的单精度浮点数 示例3:将bytes字符串转换为数值 s = b'123.45' num = float(s.decode('utf-8')) # 123.45 注意:使用struct.unpack时,需要知道数据的字节序类型(是float还是double等)。 根据要求,回答完问题后,需要提出3-5个相关问题。注意第一行必须完整输出“§§相关问题§§”,然后列出问题。 因此,我们的回答结构如下: 1. 解释如何将bytesintfloat。 2. 提供代码示例。 3. 在最后按照要求输出相关问题。 </think>在Python中,将`bytes`类型转换为数值类型(如`int`/`float`)的方法如下: ### 1. bytesint - **直接转换**(适用于ASCII数字字节): ```python b = b'123' num = int(b.decode('utf-8')) # 输出 123 (int) ``` - **大端序/小端序转换**(适用于原始二进制数据): ```python b = b'\x00\xFF' # 大端序的255 num = int.from_bytes(b, byteorder='big') # 输出 255 ``` ### 2. bytesfloat - **ASCII字符串转换**: ```python b = b'3.14' num = float(b.decode('utf-8')) # 输出 3.14 ``` - **二进制转换**(需`struct`模块): ```python import struct b = b'\x40\x49\x0f\xdb' # IEEE 754单精度浮点数(3.14159...) num = struct.unpack('>f', b)[0] # 输出 3.1415927410125732 ('>'表示大端序) ``` ### 3. 其他转换 - **布尔值**: ```python b = b'\x01' # 非空字节通常为True bool_val = bool(b) # 输出 True ``` - **十六进制字符串**: ```python b = b'\xAB\xCD' hex_str = b.hex() # 输出 'abcd' ``` ### ⚠️ 注意事项 - 处理二进制数据时需明确字节序(`big`/`little`) - 使用`struct`需匹配数据类型标识符(如`f`=单精度浮点, `d`=双精度) - 非数字字节转换会触发`ValueError`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值