Faster/better conversion than using swapbytes typecast on udp byte datastream?

9 views (last 30 days)
I am data-streaming from a netFT device using udp port. The data comes odered in chuncks of 36-bytes in a dubble array.
It is then converted to useful forcevalues using a swapbytes- typecast conversion between uint8 and int32. However this conversion is to slow for the live data stream and results in a slow buildup in the buffer. (which is solved with a dynamic buffer data collection). The swapbytes call is apprently the call that takes the longest time.
Is thera a way to do a faster/better conversion?
I can change the encoding for the data coming from the udp, but this changes the encoding to early in the conversion (the uint8 encoding rather than the int32 encoding?) and i dont know what changes in the conversion to do to accommodate the change? And would it even be faster?
If there is no alternative would it be faster to do the conversion in larger chuncks? It is now called with a for-loop with splitup data from a reading of aproxmatly 36000-bytes.
u = udpport('byte', 'IPV4');
% [some code to start data stream]
data = read(u, 36);
%u.ByteOrder="big-endian"
%u.ByteOrder="little-endian"
%% Exampel data
data =[0 5 187 8 1 136 61 48 0 0 0 0 1 67 58 246 255 127 176 76 10 231 55 137 255 240 253 91 255 229 79 46 255 240 59 110];
fx = double(swapbytes(typecast(uint8(data(13:16)), 'int32')))/1000000; %too slow, is there a faster way

Accepted Answer

Bruno Luong
Bruno Luong on 1 Feb 2024
Moved: Bruno Luong on 1 Feb 2024
Try this:
%% Exampel data
data =[0 5 187 8 1 136 61 48 0 0 0 0 1 67 58 246 255 127 176 76 10 231 55 137 255 240 253 91 255 229 79 46 255 240 59 110];
fx = double(swapbytes(typecast(uint8(data(13:16)), 'int32')))/1000000
fx = 21.1832
polyval(data(13:16),256)/1000000
ans = 21.1832
%or (this syntax migh be apted to be optimized by JIT, EE)
(data(16)+256*(data(15)+256*(data(14)+256*data(13))))/1000000
ans = 21.1832
  6 Comments
Magnus
Magnus on 2 Feb 2024
Solved the overflow issue by going back to typecast, but switching the datainput order, eliminating swapbytes. A bit slower than the more optimized solotion (about 50 times slower) but much faster than the swapbytes method. So it will do for now. Thanks for the help.
fxCast=double(typecast(uint8(data(16:-1:13)),'int32'))/1000000;
Bruno Luong
Bruno Luong on 2 Feb 2024
Edited: Bruno Luong on 2 Feb 2024
Overfow fix, using simple comparison
fxR = (DataX(i,4)+256*(DataX(i,3)+256*(DataX(i,2)+256*DataX(i,1))))/1000000;
if fxR > 2.147483647000000e3 % double(intmax('int32'))/1e6
fxR = fxR-4.294967296000000e3; % -double(intmax('uint32'))/1e6
end

Sign in to comment.

More Answers (0)

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!