Convert string to bytes
Show older comments
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 Comments
Bartosz Larzewski
on 17 Dec 2022
Moved: Stephen23
on 18 Dec 2022
Bartosz Larzewski
on 17 Dec 2022
Moved: Stephen23
on 18 Dec 2022
Bartosz Larzewski
on 17 Dec 2022
Moved: Stephen23
on 18 Dec 2022
Bartosz Larzewski
on 17 Dec 2022
Moved: Stephen23
on 18 Dec 2022
Answers (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 Comment
Walter Roberson
on 18 Dec 2022
Edited: Walter Roberson
on 18 Dec 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)
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!