Matlab 教材:二補數

Matlab 內建的進制轉換函式只能處理 253 以下的無號整數, 不能顯示負整數的二補數位元排列。 為了幫助讀者觀察書本第 D 講關於有號整數的講解, 我們在此提供一對 Matlab 函式,將 -128 到 127 之間的整數對應到 Z1 規格的位元排列。 以下 dec2z() 將 -128 到 127 之間的整數轉換成一個字元 (8 bits) 的位元排列,答案是「字串」而非數值。 而 z2dec() 相反,輸入一個字元 (8 bits) 的位元排列字串, 答案顯示那個位元排列表達的整數。

以下是 dec2z() 的 M-file 內容。

function s = dec2z(n)
% Input an integer n with -128 <= n <= 127, this function converts n
% into the bit pattern defined by the 1-byte int data type, such as
% that declared as char in C language.  The output s is a character
% array, also called a string.
%
% Shann 2004-05-12
 
% Input Validation
if ((floor(n) ~= n) | (n<-128) | (n>127))
    disp('Please input an integer between -128 and 127');
    return;
end 
 
if (n < 0)
    n = 2^8 - abs(n);
end
s = dec2bin(n, 8);

舉例來說,

dec2z(108)
得到答案 01101100,
dec2z(-42)
得到答案 11010110,都與書本舉的例子一樣。讀者可以做更多嘗試。

以下是 z2dec() 的 M-file 內容。

function n = z2dec(s)
% Input a string of at most eight (one byte) of binary digits (0 or 1),
% this function interpret the bit pattern according to 1-byte int data
% type and return the integer value in n.
%
% Shann 2004-05-12

% Input Validation
m = length(s);
if ( ~ischar(s) | m>8 | length(find(s=='0'))+length(find(s=='1'))<m )
    disp('Please input a string of at most 8 binary digits');
    return;
end

n = bin2dec(s);
if ( m==8 & s(1)=='1' )
    n = n - 2^8;
end

舉例來說,

z2dec('1101')
得到答案 13,
z2dec('11010110')
得到答案 -42。讀者可以做更多嘗試。

習題

  1. 請問 -1 在 Z1 規格的位元排列是什麼? 同樣的位元排列,以無號整數來解讀,是多少?
  2. 請問 -128 在 Z1 規格的位元排列是什麼? 同樣的位元排列,以無號整數來解讀,是多少?
[BCC16-B]
單維彰 (2004/05/12) ---
[Prev] [Next] [Up]