python列表转字节_如何在Python中将十进制数转换为字节列表

How do you turn a long unsigned int into a list of four bytes in hexidecimal?

Example...

777007543 = 0x2E 0x50 0x31 0xB7

解决方案

The simplest way I can think of is to use the struct module from within a list comprehension:

import struct

print [hex(ord(b)) for b in struct.pack('>L',777007543)]

# ['0x2e', '0x50', '0x31', '0xb7']

It's a little bit more complicated to get uppercase hex digits, but not that bad:

import string

import struct

xlate = string.maketrans('abcdef', 'ABCDEF')

print [hex(ord(b)).translate(xlate) for b in struct.pack('>L',777007543)]

# ['0x2E', '0x50', '0x31', '0xB7']

Update

Since from your comments it sounds like you may be using Python 3 — even though your question doesn't have a "python-3.x" tag — and that fact that nowadays most folks are using the later version, here's code illustrating how to do it that will work in both versions (producing uppercase hexadecimal letters):

import struct

import sys

if sys.version_info < (3,): # Python 2?

def hexfmt(val):

return '0x{:02X}'.format(ord(val))

else:

def hexfmt(val):

return '0x{:02X}'.format(val)

byte_list = [hexfmt(b) for b in struct.pack('>L', 777007543)]

print(byte_list) # -> ['0x2E', '0x50', '0x31', '0xB7']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值