python 原码反码补码移码转换
时间: 2023-12-09 19:36:31 浏览: 197
原码、反码、补码、移码与浮点.doc
5星 · 资源好评率100%
以下是Python中原码、反码、补码、移码的转换方法:
1. 原码转反码:将原码符号位不变,其余各位取反即可。
```python
def original_to_complement(original):
if original[0] == '0':
return original
else:
complement = ''
for i in range(1, len(original)):
complement += '0' if original[i] == '1' else '1'
return complement
```
2. 反码转补码:将反码最后一位加1即可。
```python
def complement_to_code(complement):
code = ''
carry = 1
for i in range(len(complement) - 1, 0, -1):
if complement[i] == '0' and carry == 1:
code = '1' + code
carry = 0
elif complement[i] == '1' and carry == 1:
code = '0' + code
else:
code = complement[i] + code
code = complement[0] + code
return code
```
3. 原码转补码:先将原码转换为反码,再将反码转换为补码即可。
```python
def original_to_code(original):
complement = original_to_complement(original)
code = complement_to_code(complement)
return code
```
4. 补码转移码:将补码最高位取出,其余各位不变即可。
```python
def code_to_excess(code):
excess = code[0]
for i in range(1, len(code)):
excess += '0' if code[i] == '0' else '1'
return excess
```
阅读全文