Convert string to bytes
Afficher commentaires plus anciens
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 commentaires
Bartosz Larzewski
le 17 Déc 2022
Déplacé(e) : Stephen23
le 18 Déc 2022
Bartosz Larzewski
le 17 Déc 2022
Déplacé(e) : Stephen23
le 18 Déc 2022
Bartosz Larzewski
le 17 Déc 2022
Déplacé(e) : Stephen23
le 18 Déc 2022
Bartosz Larzewski
le 17 Déc 2022
Déplacé(e) : Stephen23
le 18 Déc 2022
Réponses (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 commentaire
Walter Roberson
le 18 Déc 2022
Modifié(e) : Walter Roberson
le 18 Déc 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)
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!