Matlab有符号⼗进制⼩数转换为有符号⼗六进制数实现内容:
1) 通过Matlab将⽣成的随机⼩数扩⼤为20位有符号位
2) 将拓展后的数据变为补码格式: 负数变为补码,正数保持不变
3)将补码格式的⼗进制⼩数转换为有符号⼗六进制数
4)将⽣成的⼗六进制数写⼊.coe⽂件中
代码实现
% generate the random number
for i = 1: 10
M(i,1)= (-1)^i *rand(1);
end
N = length(M);
Radix      = 16;
Coeff_width = 20;
% convert the fraction number to integer
% 20 bits with 1 signed bit
M_mul = round(M.*2^(Coeff_width-1));
% convert the coefficient to complement format
for i = 1: N
if(M_mul(i) < 0)
comple_M(i) = 2^Coeff_width + M_mul(i);
else
comple_M(i) = M_mul(i);
end
end
%% write the real part .coe file
fid = fopen('M.coe','w');%File storage path
fprintf(fid,'Radix = %d; \n',Radix);
fprintf(fid,'Coefficient_Width = %d; \n',Coeff_width);
fprintf(fid,'CoefData = ');
% convert the complement format to hex format
for i = 1: N
hex_M = dec2hex(comple_M(i),5);              % 5 bits HEX = 20 bits binary
if( i < N )
for j=1:5
fprintf(fid,'%s',hex_M(j));      % print 5 bits hex data
fprintf格式
end
fprintf(fid,',\n');
else
for j=1:5
fprintf(fid,'%s',hex_M(j));
end
fprintf(fid,';\n');
end
end
fclose(fid);
结果
运⾏结果如下图所⽰,左边为⼗进制数据,右边为⼗六进制数据,数据⼀致。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。