Convert string to bytes
显示 更早的评论
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 个评论
Bartosz Larzewski
2022-12-17
移动:Stephen23
2022-12-18
Bartosz Larzewski
2022-12-17
移动:Stephen23
2022-12-18
Bartosz Larzewski
2022-12-17
移动:Stephen23
2022-12-18
Bartosz Larzewski
2022-12-17
移动:Stephen23
2022-12-18
回答(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 个评论
Walter Roberson
2022-12-18
编辑:Walter Roberson
2022-12-18
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)
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!