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

163 次查看(过去 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
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