Converting decimal to binary and vise versa

8 ビュー (過去 30 日間)
John Dimopoulos
John Dimopoulos 2018 年 1 月 9 日
コメント済み: John Dimopoulos 2018 年 1 月 10 日
Hello Matlab Community,
I have a problem. I want to create a function that converts the decimal POSITIVE number that the user gives(maximum number that the user can give is 255) to binary(8-bit accuracy for every number from 0 to 255) and also another function that takes a binary number (max: 11111111 = 255) and converts it to decimal. I'd like to use the ''for'' loop and not functions of matlab like ''dec2bin'' or ''bin2dec''.I've tried a lot but still something doesn't work.
Thanks in Advance
  5 件のコメント
John Dimopoulos
John Dimopoulos 2018 年 1 月 9 日
編集済み: John Dimopoulos 2018 年 1 月 9 日
clear;clc;
IP(1) = input('Give the first number of IP address:');
IP(2) = input('Give the second number of IP address:');
IP(3) = input('Give the third number of IP address:');
IP(4) = input('Give the fourth number of IP address:');
IP = [IP(1),IP(2),IP(3),IP(4)];
dec_nr = IP;
i = 1;
q = floor(dec_nr/2);
r = rem(dec_nr,2);
bin(i) = num2str(r(i));
while 2 <= q
dec_nr = q;
i = i + 1;
q = floor(dec_nr/2);
r = rem(dec_nr,2);
bin(i) = num2str(r);
end
bin(i + 1) = num2str(q);
bin = fliplr(bin)
John Dimopoulos
John Dimopoulos 2018 年 1 月 9 日
編集済み: John Dimopoulos 2018 年 1 月 9 日
How can I convert the IP(1),IP(2),IP(3),IP(4) decimals to binaries using 'for' loop ? Maybe writing 'for j = 1:4' in line 7, 'dec_nr = IP(j)' in line 8 and 'end' in line 21 ? If I do this I get false results when I try 2-or-less-digit numbers (example:25).What can I do ?

サインインしてコメントする。

採用された回答

Roger Stafford
Roger Stafford 2018 年 1 月 9 日
I’ll assume that the form of the binary version is a row vector, B, of eight ones or zeros, and that the "decimal" number is a double precision floating point number, D, whose value is an integer ranging from 0 to 255.
From D to B:
B = zeros(1,8);
for k = 8:-1:1
B(k) = mod(D,2);
D = (D-B(k))/2;
end
From B to D:
D = sum(B.*(2.^(7:-1:0)));
  1 件のコメント
John Dimopoulos
John Dimopoulos 2018 年 1 月 10 日
Very nice ! If I want to do the convertion in a vector of 1 line and 4 columns how to modify your code using the 'for' loop?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by