python 10进制转BCD码
时间: 2023-08-05 21:09:58 浏览: 116
微机原理实验六二进制数转换为BCD码.rar
将一个十进制数转换为BCD码可以使用以下步骤:
1. 将十进制数转换为二进制数
2. 将二进制数每4位分组,不足4位前面补0
3. 将每组二进制数转换为对应的BCD码
以下是Python代码示例:
```python
def decimal_to_bcd(decimal_num):
# 将十进制转换为二进制,去掉前缀0b
binary_num = bin(decimal_num)[2:]
# 将二进制数每4位分组,不足4位前面补0
binary_num = binary_num.zfill((len(binary_num) + 3) // 4 * 4)
binary_groups = [binary_num[i:i+4] for i in range(0, len(binary_num), 4)]
# 将每组二进制数转换为对应的BCD码
bcd_num = []
for group in binary_groups:
bcd = 0
for i in range(len(group)):
bcd += int(group[i]) * (2 ** (3 - i))
bcd_num.append(bcd)
return bcd_num
```
使用示例:
```python
print(decimal_to_bcd(123)) # [1, 2, 3]
print(decimal_to_bcd(456)) # [4, 5, 6]
print(decimal_to_bcd(789)) # [7, 8, 9]
```
阅读全文