Created
May 6, 2021 00:54
-
-
Save yuchung-chuang/662945a2fa7cdb310d9d26ecdafe3934 to your computer and use it in GitHub Desktop.
Convert a 32-bit binary number to decimal.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
input = '1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0'; %輸入32-bit二進位整數 | |
x = str2num(input); %將輸入轉成向量 | |
n = length(x); | |
y = [0, 2 .^ (n-2:-1:0)]; %2的整數冪 | |
if ~x(1) %如果是正數 | |
result = dot(x,y); %各位元與2的整數冪內積即為十進位 | |
else %如果是負數 | |
x = ~x; %取補數 | |
result = -dot(x,y)-1; %內積後取負減一 | |
end | |
result = int32(result) %將結果轉換成int32 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment