How to convert uint8 arrays to int24 efficiently

39 visualizzazioni (ultimi 30 giorni)
Hello everybody,
I have to decode data from a UDP interface. Since UDP data is received as uint8 vector, the respective bytes of the array have to be typecasted.
Unfortunately, the message is sent as signed 24 bit integer. Matlab does not support an "int24" datatype so that I have to implement the typecast myself. The typecast is called with a high frequency so that its performance is critical.
I would be happy if you could provide advice on how to solve this problem efficiently.
Beneath, I have added some "example pseudo code" that should make my problem clearer.
Thank you in advance.
% The way it works with datatypes native to matlab:
UdpByteArraySlice = uint8([10 15 124 60])
decodedMsg = typecast(UdpByteArraySlice, 'uint32')
% TODO Implement functionality that would execute an equivalent to:
UdpByteArraySlice = uint8([10 15 124])
decodedMsg = typecast(UdpByteArraySlice, 'int24') % This fails: 'int24' is not native to matlab
  1 Commento
Lasse Boenecke
Lasse Boenecke il 19 Set 2021
Here is my solution:
function Casted = TypecastInt24(Bytes)
% reshape to matrix with one column(length 3) for each int24 value
Casted = reshape(Bytes,3,[]);
% add pending zero to each column to enable native uint32 type conversion
Casted = [Casted;zeros(1,size(Casted,2))];
% execute typecast for each column and transpose to maintain row vector
Casted = typecast(Casted(:),'uint32')';
% simulate int32 value by bytehshift, convert and shift back
Casted = bitshift(Casted, 8);
Casted = bitshift(typecast(Casted,'int32'), -8);
end

Accedi per commentare.

Risposte (0)

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by