Leader

Tuesday, 2 December 2008

Converting decimal to binary and binary to decimal

See also: Base conversion of positional number systems for other conversion functions.

Download
dec2bin2.m (decimal to binary)
bin2dec2.m (binary to decimal)

Final code
See below.

Explanation
MATLAB already contains two functions to do convert between binary and decimal (dec2bin and bin2dec) but I wanted to write my own as a learning exercise – both in scripting and to learn the actual conversion method. Looking at the code in MATLABs functions is pretty fruitless for the latter. There are a couple of difference between my scripts and MATLABs, for example my dec2bin2 function automatically buffers the output to 8 bits in the form of a vector rather than a string. Conversely my bin2dec string doesn’t require a string as an input, which is convenient for certain applications.

This code is written in a way to make the processes of conversion as clear as possible - it's all done with loops, which isn't technically the best way, but it serves a purpose here!


AdSense