1. 题目
用16位二进制数表示一个十进制数字,最高位是符号位(1表示负数,并且负数用补码表示)。编程实现:输入一个十进制数字,计算输出以英文逗号(,)分割的该数字的16位二进制字符串(不足16位时,前面补0)和4位十六进制字符串(不足4位时,前面补0,如果包含字符,用大写字母表示)。当输入数字超过最大值或最小值符时,输出“NODATA”字符,输入非数字字符时,输出“INPUTERROR”字符串。例如:输入15,输出00000000001111,000F;输入-1,输出1111111111111111,FFFF,输入A,输出输入非法。
2. 解答
使用python自带函数验证参考11111Python 二进制,十进制,十六进制转换
原码转补码思路 参考here,结合求补码的过程也不难理解
## 10-2 不管固定位数
def int2bin(n): # 输入参数为整数
bin2 = ''
while n >0:
a = n%2
n = n//2
bin2 = str(a)+bin2
print(bin2)
return bin2
### 16位二进制 原码
def int2bin_16(n): ## 输入参数为整数
str1 = ''
list1 = ['0' for i in range(16)]
absn = abs(n)
for i in range(15,0,-1):
a = absn%2
absn = absn//2
list1[i] = str(a)
# print(list1)
if n < 0:
list1[0] = '1'
str1=''.join(list1)
return str1
### 原码转补码
def yuan2bu(n): # 输入为二进制原码字符串
if n[0] == '0':
return n
else:
str_bu = '1'
for j in range(15,0,-1):
if n[j]=='1':
reverseindex = j
break
for k in range(1,reverseindex):
if n[k]=='1':
str_bu += '0'
else:
str_bu += '1'
for m in range(reverseindex,16):
str_bu += n[m]
return str_bu
### 二进制转十六进制
def bin2hex(n): #输入为二进制补码字符串
str2 = ''
dict1 = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
list2 = []
for j in range(0,16,4):
sum1 = 0
for k in range(4):
sum1 = sum1 + int(n[j+k])*(2**(3-k))
list2.append(dict1[sum1])
str2=''.join(list2)
print(list2)
return str2
while(1):
num = input('Please input the num:')
# print(type(num))
flag_ifnum = True
for p in range(len(num)):
if p == 0:
if (num[p] <='9' and num[p]>= '0') or (num[p] == '-') or (num[p] == '+'):
continue
if num[p] <='9' and num[p] >= '0':
continue
else:
flag_ifnum = False
if not flag_ifnum:
print('INPUTERROR')
else:
if abs(int(num))>=2**15:
print('NODATA')
else:
bin_num_yuan = int2bin_16(int(num))
bin_num_bu = yuan2bu(bin_num_yuan)
# print(bin_num_bu)
bin_yanzheng = bin(int(num))
# print(bin_num_yuan)
# print(bin_yanzheng)
hex_num = bin2hex(bin_num_bu)
# print(hex_num)
hex_num_yanzheng = hex(int(num))
# print(hex_num_yanzheng)
print(bin_num_bu+','+hex_num)
print('check_bin',bin_yanzheng)
print('check_hex',hex_num_yanzheng)