使用16位块将数字表示为字节

时间:2016-08-24 20:38:56

标签: python python-3.x

我希望将683550(0xA6E1E)之类的数字转换为b'\x1e\x6e\x0a\x00',其中数组中的字节数是2的倍数,而bytes对象的len只有这么长因为它需要代表数字。

据我所知:

"{0:0{1}x}".format(683550,8)

,并提供:

'000a6e1e' 

2 个答案:

答案 0 :(得分:2)

使用.tobytes - 方法:

num = 683550
bytes = num.to_bytes((num.bit_length()+15)//16*2, "little")

答案 1 :(得分:0)

使用python3:

def encode_to_my_hex_format(num, bytes_group_len=2, byteorder='little'):
  """
  @param byteorder can take the values 'little' or 'big'
  """
  bytes_needed = abs(-len(bin(num)[2: ]) // 8)

  if bytes_needed % bytes_group_len:
    bytes_needed += bytes_group_len - bytes_needed % bytes_group_len

  num_in_bytes = num.to_bytes(bytes_needed, byteorder)
  encoded_num_in_bytes = b''

  for index in range(0, len(num_in_bytes), bytes_group_len):
    bytes_group = num_in_bytes[index: index + bytes_group_len]

    if byteorder == 'little':
      bytes_group = bytes_group[-1: -len(bytes_group) -1 : -1]

    encoded_num_in_bytes += bytes_group

  encoded_num = ''

  for byte in encoded_num_in_bytes:
    encoded_num += r'\x' + hex(byte)[2: ].zfill(2)

  return encoded_num

print(encode_to_my_hex_format(683550))