使用 python 将十六进制转储到 YAML
问题描述
现在我正在转储到 YAML 文档中.它在大多数情况下都在正常工作.当我尝试转储诸如0x2A"之类的十六进制时,它会转换为 42.有没有办法保持它的十六进制格式?可悲的是,字符串不会起作用.而 int(0x2A, 16) 也只是给了我一个 42.
Now I'm dumping into a YAML document. It's working as it should for the most part. When I try to dump a hexadecimal such as "0x2A" it converts to 42. Isn't there any way to maintain it's hexadecimal format? A string won't work sadly. And int( 0x2A, 16) also just gives me a 42.
解决方案
您可能正在寻找 hex(0x2a) == hex(42) == '0x2a'
.
除非您正在寻找一种方法来说服您现有的转储函数使用十六进制而不是十进制表示法...
Unless you're looking for a way to convince your existing dumping function to use hexadecimal instead of decimal notation...
回答您在下面的评论,如果问题是您想要十六进制数字的大写字母(但 0x
的小写字母),那么您必须使用字符串格式.您可以选择以下选项之一:
Answering to your comment below, if the problem is that you want upper case letters for the hexadecimal digits (but lower case for the 0x
) then you have to use string formatting. You can choose one of the following:
"0x%02X" % 42 # the old way
"0x{:02X}".format(42) == "0x2A" # the new way
在这两种情况下,您都必须显式打印 0x
,后跟至少两位大写的十六进制数字,如果您的数字只有一位,则左填充零数字.这由 02X
格式表示,与 C 的 printf
中的格式相同.
In both cases, you'll have to print the 0x
explicitly, followed by a hexadecimal number of at least two digits in upper case, left-padded with a zero if your number has only one digit. This is denoted by the format 02X
, same as in C's printf
.
相关文章