Matlab 有符號16進制數(16進制補碼)轉10進制

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)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章