Simulink convert datatype to array of bytes

15 visualizzazioni (ultimi 30 giorni)
Joe Holdsworth
Joe Holdsworth il 30 Gen 2018
Commentato: Walter Roberson il 26 Mar 2025
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.

Risposte (1)

Aashray
Aashray il 26 Mar 2025
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 Commento
Walter Roberson
Walter Roberson il 26 Mar 2025
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.

Accedi per commentare.

Categorie

Scopri di più su Numeric Types in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by