필터 지우기
필터 지우기

Convert String and Timestamp into Bytes

조회 수: 16 (최근 30일)
PTP
PTP 2016년 2월 1일
댓글: Walter Roberson 2020년 2월 10일
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
Gabriel Hernandez 2020년 2월 8일
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