Convert String and Timestamp into Bytes

16 次查看(过去 30 天)
Hello Everyone,
How to Convert String data or Timestamp data to bytes and then send those bytes to another Laptop and on the another laptop regenerate the data back to String so that it is readable to Humans. Here is my code:
TheTime = now;
dv = datevec(TheTime);
dv(6) = 0;
reconstructed_time = datenum(dv);
timediff = TheTime - reconstructed_time;
diff_secs = timediff * 24*60*60;
s = sprintf('Master node sent Sync Message at Time %s%09.6f', datestr(dv, 'yyyy-mm-dd HH:MM:'), diff_secs)
When I run it, the result is:
Master node sent Sync Message at Time 2016-02-01 13:49:51.967210
How can I convert this result to bits/Bytes and then send these bytes to another laptop via UDP.
Then reconvert the Bytes to the String so that humans can read it.

采纳的回答

Walter Roberson
Walter Roberson 2016-2-1
sBytes = uint8(s);
Send sBytes
To reconstruct,
s = char(sBytes);
  2 个评论
Gabriel Hernandez
I am getting the following error:
Error using uint8
Conversion to uint8 from string is not possible.
Walter Roberson
Walter Roberson 2020-2-10
In the original code, the way that s was created, it was not possible for it to be string, only character vector.
If you has an s that is a string object, then assuming the variable is named s, then
uint8(reshape(char(s), 1, []))
This can be simplified under the circumstance that s is a scalar string object; in that case
uint8(s{1})
In the case where s is a non-scalar string object, then in order to reconstruct to a string array of the same size, you will need to know the size of the string array. Also, you would need additional work in the case where some of the string entries ended with spaces that you wanted to preserve, as the conversion of non-scalar string array to bytes requires padding the strings out to all be the same length (unless you are willing to choose a character that can never appear inside the strings, in which case you can use that character as a delimiter.)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by