Convert string to bytes
Mostrar comentarios más antiguos
Hello,
How can I convert string variable like b'\xfd\xfd\xfd\xfd\xfd into row vector [253, 253, 253, 253,253]?
I would like to convert ping message from Ping Sonar made by BlueRobotics.
Greeting :)
4 comentarios
Bartosz Larzewski
el 17 de Dic. de 2022
Movida: Stephen23
el 18 de Dic. de 2022
Bartosz Larzewski
el 17 de Dic. de 2022
Movida: Stephen23
el 18 de Dic. de 2022
Bartosz Larzewski
el 17 de Dic. de 2022
Movida: Stephen23
el 18 de Dic. de 2022
Bartosz Larzewski
el 17 de Dic. de 2022
Movida: Stephen23
el 18 de Dic. de 2022
Respuestas (2)
To convert a string variable like b'\xfd\xfd\xfd\xfd\xfd' into a row vector of integers, you can use the typecast function in MATLAB. This function allows you to convert variables to a different data type, in this case to an array of unsigned 8-bit integers.
Here is an example of how you can use the typecast function to convert the string variable to a row vector:
% Define the string variable
string_variable = b'\xfd\xfd\xfd\xfd\xfd';
% Convert the string variable to an array of unsigned 8-bit integers
row_vector = typecast(string_variable, 'uint8');
% Print the result
disp(row_vector)
1 comentario
Walter Roberson
el 18 de Dic. de 2022
Editada: Walter Roberson
el 18 de Dic. de 2022
MATLAB does not support b' syntax, and does not permit char or string() to be typecast()
filename = 'płaska_2m_#2profile.txt'; %careful, that is not an L
S = readlines(filename);
%first convert escaped ' and " to their hex equivalents
%then strip off b"..." and b'...' to just the content
normalized = regexprep(S, {char("\\'"), '\\"', '^b"([^"]+)"', char("^b'([^']+)'")}, {'\\x27', '\\22', '$1', '$1'}, 'lineanchors');
%now convert \x.. to the character equivalent
%do NOT just put the whole line through sprintf! The text contains things
%like \xfdC and sprintf will extend the hex as far as possible instead of
%just using two hex digits
unhexed = regexprep(normalized, '(\\x..)', '${sprintf($1)}');
as_bytes = arrayfun(@(str)0+char(str), unhexed, 'uniform', 0)
Categorías
Más información sobre Data Type Conversion en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!