python在特定位宽下,有符号数的10进制,2进制,16进制之间的转换。

16进行转换为10进制

# singed_bin2dec.py
import os,sys,re

data = sys.argv[1]; # hex data

try:
    width = int(sys.argv[2]);
except IndexError:
    width = 7;

dec_data = int(data, 16);
print(dec_data);
if(dec_data>2**(width-1)-1_:
    dec_data = 2**width-dec_data;
    print(-dec_data);

2进制转10进制

# singed_bin2dec.py
import os,sys,re
data = sys.argv[1]; # hex data

try:
    width = int(sys.argv[2]);
except IndexError:
    width = 7;

if(len(data)!=width):
    print("\ndata length is wrong.....\n");
    sys.exit();

dec_data = int(data, 2);
print(dec_data);
if(dec_data>2**(width-1)-1_:
    dec_data = 2**width-dec_data;
    print(-dec_data);

10进制转16进制

# singed_dec2hex.py
import os,sys,re

data = int(sys.argv[1]);

try:
    width = int(sys.argv[2]);
except IndexError:
    width = 7;

if(data>2**(width-1)-1):
    print("\ndata is too big .......\n");
    sys.exit();
if(data<-2**(width-1)):
    print("\ndata is too small.....\n");
    sys.exit();

if(data<0):
    data = 2**width+data;
    bin_data = bin(data);
    bin_data = bin_data[2:len(bin_data)];
    hex_data = hex(int(bin_data,2));
    print(hex_data);
else:
    bin_data = bin(data);
    bin_data = bin_data[2:len(bin_data)];
    for i in range(0,width-len(bin_data)):
        bin_data = '0' + bin_data;
    
    hex_data = hex(int(bin_data,2));
    hex_data = hex_data[2:len(hex_data)];
    for i in range(0,(width+3)/4-len(hex_data)):
        hex_data = '0' + hex_data;
    print('0x'+tmp);

10进制转2进制

# singed_dec2hex.py
import os,sys,re

data = int(sys.argv[1]);

try:
    width = int(sys.argv[2]);
except IndexError:
    width = 7;

if(data>2**(width-1)-1):
    print("\ndata is too big .......\n");
    sys.exit();
if(data<-2**(width-1)):
    print("\ndata is too small.....\n");
    sys.exit();

if(data<0):
    data = 2**width+data;
    bin_data = bin(data);
    bin_data = bin_data[2:len(bin_data)];
    print(bin_data);
else:
    bin_data = bin(data);
    bin_data = bin_data[2:len(bin_data)];
    for i in range(0,width-len(bin_data)):
        bin_data = '0' + bin_data;
    
    print(bin_data);

 

posted @ 2018-05-05 16:01  下夕阳  阅读(4772)  评论(0编辑  收藏  举报