coverting binary to decimal and vise versa

Hello, I'm currently learing about binary code, and how to covert it into numbers. I know MATLAB has built in commands for this, but can I write a script that could do this for me without the commands? I'd really appreciate any help on the matter. Thank you for your time.

Answers (2)

Yes, you are quite welcome to write your own version of dec2bin() using lower level functions. You might use a for loop, rem(), and functions like that.
James Tursa
James Tursa on 9 Jul 2015
Edited: James Tursa on 9 Jul 2015
Assuming you are only interested in positive integers (that are not too large), realize that mod(x,2) will pick off the least significant binary digit. You just need to figure out how to modify x with each iteration to get the next binary digit with another mod(x,2). Etc.
For the reverse problem, you simply need to multiply your binary digits by successive powers of 2 and add them up.

Categories

Find more on Argument Definitions in Help Center and File Exchange

Asked:

on 9 Jul 2015

Edited:

on 9 Jul 2015

Community Treasure Hunt

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

Start Hunting!