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

조회 수: 142 (최근 30일)
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.

채택된 답변

MathWorks Support Team
MathWorks Support Team 2009년 6월 27일
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)')

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R13SP1

Community Treasure Hunt

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

Start Hunting!

Translated by