How can I convert an array of binary values into the corresponding decimal number within MATLAB?

158 views (last 30 days)
I have an array of values that represents the binary value of a number. For example:
x = [1 0 0 0 0 0 0 0];
is used to represent the binary value 10000000, which is the decimal value 128. The BIN2DEC function is used to convert binary strings into decimal numbers. I would like to convert my array into the corresponding decimal value.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
You can convert the array to a decimal number by first converting it into a binary string, then using the BIN2DEC function to convert the string into a number:
x = [1 0 0 0 0 0 0 0];
% convert x to a string array
str_x = num2str(x);
% remove the spaces in the string, so it
% becomes '10000000'
str_x(isspace(str_x)) = '';
% now use BIN2DEC to convert the binary
% string to a decimal number
y = bin2dec(str_x);
For MATLAB 7.0 (R14) and releases after that, BIN2DEC ignores any space (' ')
characters in the input string. Hence, the following step is not required in the above code:
str_x(isspace(str_x)) = '';
Please note that the BIN2DEC function works with strings of size less than 52 bits.
To convert a binary string with more than 52 bits, you would need to use the symbolic Math Toolbox in MATLAB.
For example, a binary string can be converted using the text2int function in MATLAB 7.8 (R2009a).
z = evalin(symengine,'text2int("1111000101111100010111110001011111000001011111000101010",2)')

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Products


Release

R13SP1

Community Treasure Hunt

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

Start Hunting!