黑马程序员技术交流社区

标题: Python 内置函数进制转换的用法(十进制转二进制、八进制、十六进制) [打印本页]

作者: lalah    时间: 2019-7-27 19:36
标题: Python 内置函数进制转换的用法(十进制转二进制、八进制、十六进制)
使用Python内置函数:bin()、oct()、int()、hex()可实现进制转换。

先看Python官方文档中对这几个内置函数的描述:

bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

oct(x)
Convert an integer number to an octal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

int([number | string[, base]])
Convert a number or string to an integer. If no arguments are given, return 0. If a number is given, return number.__int__(). Conversion of floating point numbers to integers truncates towards zero. A string must be a base-radix integer literal optionally preceded by ‘+' or ‘-‘ (with no space in between) and optionally surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with ‘a' to ‘z' (or ‘A' to ‘Z') having values 10 to 35. The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).

hex(x)
Convert an integer number to a hexadecimal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

↓        2进制        8进制        10进制        16进制
2进制        -        bin(int(x, 8))        bin(int(x, 10))        bin(int(x, 16))
8进制        oct(int(x, 2))        -        oct(int(x, 10))        oct(int(x, 16))
10进制        int(x, 2)        int(x, 8)        -        int(x, 16)
16进制        hex(int(x, 2))        hex(int(x, 8))        hex(int(x, 10))        -
bin()、oct()、hex()的返回值均为字符串,且分别带有0b、0o、0x前缀。

Python进制转换(二进制、十进制和十六进制)实例

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2/10/16 base trans. wrote by srcdog on 20th, April, 2009
# ld elements in base 2, 10, 16.

import os,sys

# global definition
# base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]

# bin2dec
# 二进制 to 十进制: int(str,n=10)
def bin2dec(string_num):
return str(int(string_num, 2))

# hex2dec
# 十六进制 to 十进制
def hex2dec(string_num):
return str(int(string_num.upper(), 16))

# dec2bin
# 十进制 to 二进制: bin()
def dec2bin(string_num):
num = int(string_num)
mid = []
while True:
if num == 0: break
num,rem = divmod(num, 2)
mid.append(base[rem])

return ''.join([str(x) for x in mid[::-1]])

# dec2hex
# 十进制 to 八进制: oct()
# 十进制 to 十六进制: hex()
def dec2hex(string_num):
num = int(string_num)
mid = []
while True:
if num == 0: break
num,rem = divmod(num, 16)
mid.append(base[rem])

return ''.join([str(x) for x in mid[::-1]])

# hex2tobin
# 十六进制 to 二进制: bin(int(str,16))
def hex2bin(string_num):
return dec2bin(hex2dec(string_num.upper()))

# bin2hex
# 二进制 to 十六进制: hex(int(str,2))
def bin2hex(string_num):
return dec2hex(bin2dec(string_num))
以下代码用于实现十进制转二进制、八进制、十六进制:

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.jb51.net

# 获取用户输入十进制数
dec = int(input("输入数字:"))

print("十进制数为:", dec)
print("转换为二进制为:", bin(dec))
print("转换为八进制为:", oct(dec))
print("转换为十六进制为:", hex(dec))
执行以上代码输出结果为:

python3 test.py
输入数字:5
十进制数为:5
转换为二进制为: 0b101
转换为八进制为: 0o5
转换为十六进制为: 0x5

python3 test.py
输入数字:12
十进制数为:12
转换为二进制为: 0b1100
转换为八进制为: 0o14
转换为十六进制为: 0xc

具体实现

十进制到二进制:

def dec2bin(num):
l = []
if num < 0:
return '-' + dec2bin(abs(num))
while True:
num, remainder = divmod(num, 2)
l.append(str(remainder))
if num == 0:
  return ''.join(l[::-1])
十进制到八进制:

def dec2oct(num):
l = []
if num < 0:
return '-' + dec2oct(abs(num))
while True:
num, remainder = divmod(num, 8)
l.append(str(remainder))
if num == 0:
  return ''.join(l[::-1])
十进制到十六进制:

base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]
def dec2hex(num):
l = []
if num < 0:
return '-' + dec2hex(abs(num))
while True:
num,rem = divmod(num, 16)
l.append(base[rem])
if num == 0:
  return ''.join(l[::-1])
python进2、8、16制转换源码

def cn(x):
return x.decode('utf-8')
a=int(raw_input(cn('请输入要转换的数字:')))
b=int(raw_input(cn('请输入要转换的进制:')))
def x(n,k):
if k==16:
  d=n
  s=""
  while d!=0:
   d,f=divmod(d,k)
   if f==10:
    f='a'
   if f==11:
    f='b'
   if f==12:
    f='c'
   if f==13:
    f='d'
   if f==14:
    f='e'
   if f==15:
    f='f'
   s=str(f)+s
  return s
elif k==2 or k==8:
  d=n
  s=""
  while d!=0:
   d,f=divmod(d,k)
   s=str(f)+s
  return s
c=x(a,b)
print c
#本程序仅支持2,8,16进制,若想支持更多进制请自己动脑该代码吧!
python 十进制整数转换为任意进制(36以内)

def baseN(num, b):
  return ((num == 0) and "0") or (baseN(num // b, b).lstrip("0") + "0123456789
作者: 夜听雨    时间: 2019-8-14 10:31
发光并非太阳的专利,你也可以发光。加油
作者: 柠檬leung不酸    时间: 2019-8-22 15:28
不忘初心,坚持




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2