How can I convert an array of binary values into the corresponding decimal number within MATLAB?
141 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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.
Respuesta aceptada
MathWorks Support Team
el 27 de Jun. de 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)')
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!