Code covered by the BSD License  

Highlights from
Efficient convertors between binary and decimal numbers

4.0

4.0 | 1 rating Rate this file 10 Downloads (last 30 days) File Size: 1.48 KB File ID: #26447

Efficient convertors between binary and decimal numbers

by Zacharias Voulgaris

 

21 Jan 2010

Alternatives to the built-in functions bin2dec & dec2bin, exhibiting a somewhat faster performance.

| Watch this File

File Information
Description

These programs were developed for fast conversions between binary and decimal integers (there are other programs by fellow Matlab-users, dealing with fractions). They can be useful when the binary numbers are in vector form instead of strings.

b2d takes a binary number in the form of an array and calculates the equivalent decimal one. Nothing fancy, but quite effective as a component of a program that needs to be efficient in terms of computational overhead.

d2b is the symmetrical program, taking a decimal number and providing the equivalent binary one, in the form of an array.

Usage: y = b2d(x), y = d2b(x)

MATLAB release MATLAB 7.8 (R2009a)
Other requirements These programs are quite simple, so they can probably run smoothly on even the earliest releases of Matlab.
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (3)
30 Sep 2010 Roberto Olmi

A little bug for the trivial input value: x=1. Add these lines to fix:
if x==1
   y=1;
   return
end

14 Mar 2011 Ali

More correct version:

function y = d2b(x)

% Convert a decimanl number into a binary array
%
% Similar to dec2bin but yields a numerical array instead of a string and is found to
% be rather faster

if x==1
   y=1;
   return
end

c = ceil(log(x)/log(2)) + 1; % Number of divisions necessary ( rounding up the log2(x) )
y(c) = 0; % Initialize output array
for i = 1:c
    r = floor(x / 2);
    y(c+1-i) = x - 2*r;
    x = r;
end

% If there is a preceding one, remove it.
if(y(1) == 0)
    y(1) = [];
end

22 Mar 2012 Marc Lalancette

Actually, the bug was for any power of 2 (1, 2, 4, ...). Ali's modification works, but a more elegant fix is:
c = floor(log2(x)) + 1;
No need for any other modification from original code (no special case for 1, no need to remove preceding zeros).

Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
binary Zacharias Voulgaris 22 Jan 2010 10:37:33
decimal Zacharias Voulgaris 22 Jan 2010 10:37:34
conversion Zacharias Voulgaris 22 Jan 2010 10:37:34

Contact us at files@mathworks.com