getting int16s that are stored in two uint8s

조회 수: 17 (최근 30일)
Matt Nickels
Matt Nickels 2022년 4월 27일
댓글: Matt Nickels 2022년 4월 28일
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');

채택된 답변

Steven Lord
Steven Lord 2022년 4월 27일
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
Matt Nickels
Matt Nickels 2022년 4월 28일
Thank you! It appears this worked for unsigned to signed 2's compliment as well so that is great!

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by