Python 使用Coden模块进行二进制、十六进制和十进制之间的转换
coden是由Tanmay Earappa开发的Python库,用于密钥编码(解码和编码)。该模块提供了进行编码转换的功能。以下是几个函数及其功能:
- coden.secret(): 基于mode参数的输入,用于解码或编码密钥。
-
hex_to_bin(): 用于将十六进制转换为二进制。
-
int_to_bin(): 用于将十进制转换为二进制。
-
int_to_hex(): 用于将十进制转换为十六进制。
使用pip安装Coden模块
使用pip命令可以轻松安装此模块,然后通过导入模块即可访问Python解释器中的转换功能。只需在命令提示符中运行以下命令即可获取Coden模块。
pip install --coden
在本文中,我们将使用Coden模块讨论二进制、十六进制和十进制数之间的转换。
十六进制转二进制
通过使用hex_to_bin()函数,我们可以将十六进制数转换为二进制数。
示例
输入的十六进制数为 f1ff ,预期的二进制数将是 1111000111111111 。
# importing the coden module
import coden
hexadecimal_number="f1ff"
print("Input Hexadecimal Number:", hexadecimal_number)
binary_output = coden.hex_to_bin(hexadecimal_number)
print('Binary Output:', binary_output)
输出
Input Hexadecimal Number: f1ff
Binary Output: 1111000111111111
十六进制转十进制
函数coden.hex_to_int()将一个十六进制数转换为十进制数。
示例
我们来取一个十六进制数并将其转换为十进制。
import coden
hexadecimal_number="f1ff63"
print("Input Hexadecimal Number:", hexadecimal_number)
decimal_number = coden.hex_to_int(hexadecimal_number)
print('Decimal Output:', decimal_number)
输出
Input Hexadecimal Number: f1ff63
Decimal Output: 15859555
二进制转十六进制转换
函数coden.bin_to_hex()将二进制数转换为十六进制数。
示例
这里我们将取一个二进制数,预期的十六进制数将是abc123efff。
import coden
binary_number = '001010101111000001001000111110111111111111'
print("Input Binary Number:", binary_number)
# Convert Binary Number to Hexadecimal Number
hexadecimal_output = coden.bin_to_hex(binary_number)
print('Hexadecimal Output:', hexadecimal_output)
输出
Input Binary Number: 001010101111000001001000111110111111111111
Hexadecimal Output: abc123efff
十进制转二进制转换
使用coden.int_to_bin()函数可以将十进制数转换为二进制数。
示例
让我们取一个十进制数并将其转换为二进制数。
import coden
decimal_number = 16227
print("Input decimal Number:", decimal_number)
binary_output = coden.int_to_bin(decimal_number)
print('Binary Output',binary_output)
输出
Input decimal Number: 16227
Binary Output 11111101100011
十进制转十六进制转换
使用int_to_hex()函数,我们可以将十进制数转换为十六进制数。
示例
让我们将一个十进制数转换为十六进制数。
import coden
decimal_number = 16227
print("Input decimal Number:", decimal_number)
hexadecimal_output = coden.int_to_hex(decimal_number)
print('Hexadecimal Output',hexadecimal_output)
输出
Input decimal Number: 16227
Hexadecimal Output 3f63
二进制转十进制转换
coden.bin_to_int()函数将执行二进制转十进制转换。
示例
通过使用bin_to_int()方法,我们将一个二进制数转换为十进制数。
import coden
binary_number = '001010101111000001001000111110111111111111'
print("Input Binary Number:", binary_number)
decimal_output = coden.bin_to_int(binary_number)
print('Decimal Output:', decimal_output)
输出
Input Binary Number: 001010101111000001001000111110111111111111
Decimal Output: 737679765503
我们已经讨论了与二进制、十六进制和十进制数之间的代码转换相关的所有编码方法。