Simulink convert datatype to array of bytes

조회 수: 20 (최근 30일)
Joe Holdsworth
Joe Holdsworth 2018년 1월 30일
댓글: Walter Roberson 2025년 3월 26일
All I want to do is convert a uint16 (and perhaps other data types) to an array of bytes. There does not appear to be a block for this.
At the moment I am using typecast function, but is this supported by code generation for embedded coder?
Thanks.

답변 (1개)

Aashray
Aashray 2025년 3월 26일
As far as I know, there is no dedicated Simulink block for directly converting a uint16 to an array of bytes. But at the same time, a MATLAB Function block inside Simulink can be used, in which you can write logic to convert a uint16 input to an array of uint8 bytes as output. The code for the workaround is as below, where we extract the MSB (Most Significant Byte) and LSB (Least Significant Byte) using bit shifting and masking:
function byteArray = uint16_to_bytes(value)
% Ensure the value is a uint16
if ~isa(value, 'uint16')
error('Input must be a uint16 value');
end
% Convert uint16 to an array of uint8 bytes
byteArray = uint8([bitshift(value, -8), bitand(value, 255)]);
end
You can place this code inside a MATLAB Function block in your Simulink model. The block will take a uint16 input and produce an array of uint8 bytes as output, I am also attaching a sample Simulink model for demonstration.
value = uint16(12345);
byteArray = uint16_to_bytes(value);
disp(byteArray);
48 57
The “typecast()” function is supported by embedded coder, but you need to check the compatibility for it, thus manual approach is a fine workaround. Moreover, it gives much greater control over how bytes are extracted.
I am attaching documentation links for the functions I have used, which might turn out to be helpful:
  1. "bitshift()" function : https://www.mathworks.com/help/matlab/ref/bitshift.html
  2. "bitand()" function: https://www.mathworks.com/help/matlab/ref/bitand.html
  3. "error()" function: https://www.mathworks.com/help/matlab/ref/error.html
  댓글 수: 1
Walter Roberson
Walter Roberson 2025년 3월 26일
In the case where the value array is a vector, then
byteArray = reshape([uint8(bitshift(value(:).',-8)); uint8(bitand(value(:).',255))], 1, []);
presuming that you want a row vector of output.
typecast() itself gives a row vector result if the input is row vector, and gives a column vector result if the input is column vector.
The (:).' operations can potentially be simplified if the orientation of the input vector is known.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by