Skip to content

Instantly share code, notes, and snippets.

@yuchung-chuang
Created May 6, 2021 00:54
Show Gist options
  • Save yuchung-chuang/662945a2fa7cdb310d9d26ecdafe3934 to your computer and use it in GitHub Desktop.
Save yuchung-chuang/662945a2fa7cdb310d9d26ecdafe3934 to your computer and use it in GitHub Desktop.
Convert a 32-bit binary number to decimal.
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