[英]Converting decimal to Formatted Binary and Hex - Python
How do i convert the decimal value into formatted Binary value and Hex value 如何将十进制值转换为格式化的二进制值和十六进制值
usually i do it this way 通常我是这样
binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
print binary(17)
>>>> 10001
print binary(250)
>>>> 11111010
but i wanted to have 8 binary digits for any value given (0-255 only) ie I need to append '0' to the beginning of the binary number like the examples below 但是我想给定任何值的8个二进制数字(仅0-255),即我需要在二进制数的开头附加“ 0”,如下例所示
7 = 0000 1111
10 = 0000 1010
250 = 1111 1010
and even i need to convert to the hex starting with 0x 甚至我需要转换为以0x开头的十六进制
7 = 0x07
10 = 0x0A
250 = 0xFA
Alternative solution is to use string.format 替代解决方案是使用string.format
>>> '{:08b}'.format(250)
'11111010'
>>> '{:08b}'.format(2)
'00000010'
>>> '{:08b}'.format(7)
'00000111'
>>> '0x{:02X}'.format(7)
'0x07'
>>> '0x{:02X}'.format(250)
'0xFA'
You can use the built-in functions bin()
and hex()
as follows: 您可以如下使用内置函数bin()
和hex()
:
In[95]: bin(250)[2:]
Out[95]: '11111010'
In[96]: hex(250)
Out[96]: '0xfa'
You can use bin(), hex() for binary and hexa-decimal respectively, and string.zfill() function to achieve 8 bit binary number. 您可以分别对二进制和十六进制使用bin(),hex()和string.zfill()函数来实现8位二进制数。
>>> bin(7)[2:].zfill(8)
'00000111'
>>> bin(10)[2:].zfill(8)
'00001010'
>>> bin(250)[2:].zfill(8)
'11111010'
>>>
>>> hex(7)
'0x7'
>>> hex(10)
'0xa'
>>> hex(250)
'0xfa'
I assume that leading 0's were not required in hexadecimals. 我假设十六进制不需要前导0。
You can use format: 您可以使用以下格式:
'{:08b}'.format(5)
'{:#x}'.format(12)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.