16进制补码求10进制
% hex(complementary code) to dec
input_hex = 'FFFFFF9C';
input_bin = dec2bin(hex2dec(input_hex),16);%
my_code = input_bin;
nbit = length(input_bin);
if my_code(1) == '0' % 是一个正整数
out_dec = bin2dec(my_code);
else
tmp = my_code(2:nbit);
pos0 = find(tmp == '0');% find position 0
pos1 = find(tmp == '1');
my_code(pos0+1) = '1';
my_code(pos1+1) = '0'; % 取反
% c(b == '0') = '1';
% c(b == '1') = '0';
% c(1) = '1';
d = bin2dec( my_code(2:nbit) ) + 1; % +1
d = dec2bin(d,nbit); % absolute value(dec)
d = d(2:nbit); % base code(without mark )
out_dec = -bin2dec(d);
end
fprintf('16进制补码表示 %s 的十进制数是 %d.\n',input_hex,out_dec)
10进制求16进制补码
% dec 2 hex 求补码(生成的结果是字符串)
input_dec = -100;
out_hex = 0;
if (input_dec >= 0)
out_bin = dec2bin(input_dec, 16);
out_hex = dec2hex(input_dec,4);
else
tmp_d = dec2bin(-input_dec, 16);
c = tmp_d;
c(tmp_d == '0') = '1';
c(tmp_d == '1') = '0';
c(1) = '1';
d = bin2dec(c) + 1;
out_bin = dec2bin(d,16);
out_hex = dec2hex(d,4); %% 4 位16进制数
end
fprintf('%d 的补码十六进制是 %s.\n',input_dec,out_hex)