在Python中将整数转换为十六进制 [英] Convert integer to hex in Python

查看:1163
本文介绍了在Python中将整数转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我希望将整数 3892 转换为给定格式的十六进制代码,结果 \x00\x00\x0F \x34 。这是怎么实现的?

解决方案

您正在转换为数字的二进制表示,而不是十六进制表示Python将以十六进制显示字节)。使用 struct 模块
$ b 示例: struct.pack('> I',3892)
'\x00\x00\x0f4'
>>> struct.pack('> I',4314)
'\x00\x00\x10\xda'

请注意,'4'的ASCII码是0x34,如果python只是一个非空字符,它只会显示带有 \ x 可打印的字符。由于0x34是可打印的,因此python会输出 4 来代替。

上面的格式代码中的

'>'表示' big endian'和'I'是一个无符号的int转换(4字节)。


In Python I want to tranform the integer 3892 into a hexcode with the given format and the result \x00\x00\x0F\x34. How can this be achieved?

解决方案

You are converting to a binary representation of the number, not so much a hex representation (although Python will display the bytes as hex). Use the struct module for such conversions.

Demonstration:

>>> struct.pack('>I', 3892)
'\x00\x00\x0f4'
>>> struct.pack('>I', 4314)
'\x00\x00\x10\xda'

Note that the ASCII code for '4' is 0x34, python only displays bytes with a \x escape if it is a non-printable character. Because 0x34 is printable, python outputs that as 4 instead.

'>' in the formatting code above means 'big endian' and 'I' is an unsigned int conversion (4 bytes).

这篇关于在Python中将整数转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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