Filter löschen
Filter löschen

Convert String and Timestamp into Bytes

16 Ansichten (letzte 30 Tage)
PTP
PTP am 1 Feb. 2016
Kommentiert: Walter Roberson am 10 Feb. 2020
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.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 1 Feb. 2016
sBytes = uint8(s);
Send sBytes
To reconstruct,
s = char(sBytes);
  2 Kommentare
Gabriel Hernandez
Gabriel Hernandez am 8 Feb. 2020
I am getting the following error:
Error using uint8
Conversion to uint8 from string is not possible.
Walter Roberson
Walter Roberson am 10 Feb. 2020
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.)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by