getting int16s that are stored in two uint8s

16 visualizzazioni (ultimi 30 giorni)
I have A LOT of int16 data that is currently stored in a vector of uint8's called data. I need to interpret the binary data in each pair of uint8's as an int16 value and get a new vector that is half the length. I attempted the following, which seems to work for small amounts of data, but when I run it on my very large data vector, matlab seems to hang/freeze, or at least not come back within my patience window :) Looking for a more efficient way to accomplish the same thing. I do not have fixed point (I thought I might be able to do it with bin2num and quantizer) so looking for other ways. I've seen similar things done with bitshift and add, but that was unsigned to unsigned. Not sure how to do that with trying to get an int16 out instead of a uint16. Maybe there is something to "properly" go from uint16 to int16 in a two's compliment sense?
%data is 787124x1 uint8
%bindata is 2097152x1 char
%sdata should come back as a 1x1 cell array with a 131072x1 int16 vector inside of it, but it doesn't seem to get there in a reasonable time.
bindata = dec2bin(data,8).';
bindata = bindata(:);
sdata = textscan(bindata, '%16bs16');

Risposta accettata

Steven Lord
Steven Lord il 27 Apr 2022
Use typecast, potentially along with swapbytes.
x = [0xbe 0xef] % Sample data
x = 1×2
190 239
class(x) % Two 8-bit unsigned integers
ans = 'uint8'
y = typecast(x, 'uint16') % One 16-bit unsigned integer
y = uint16 61374
z = swapbytes(y) % Also a 16-bit unsigned integer
z = uint16 48879
format hex % Look at the hex patterns
x
x = 1×2
be ef
y
y = uint16
efbe
z
z = uint16
beef
  1 Commento
Matt Nickels
Matt Nickels il 28 Apr 2022
Thank you! It appears this worked for unsigned to signed 2's compliment as well so that is great!

Accedi per commentare.

Più risposte (0)

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by