How to covert int32 or int16 to uint8?

156 ビュー (過去 30 日間)
Hassan Iqbal
Hassan Iqbal 2016 年 10 月 17 日
回答済み: Steven Lord 2016 年 10 月 17 日
I want to read a wav file containing 16 bit samples and covert it to 8 bit samples and write back. Once I have read the 16 bit samples into an array, how do I convert them to 8 bit samples? The 16 bit are signed while the 8 bit are unsigned. Yes, data will be lost. What built in function does such coversion?
For some reason when I read in the .wav file, the sample data is stored as an matrix of type double. Why?

回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 10 月 17 日
By default, wavread() automatically converts samples from their internal format into the range -1 <= x < 1 by scaling and shifting. You can convert that double to uint8 by
[samples, Fs] = wavread('YourFile.wav');
samples8 = uint8( (samples + 1)/2 * 255 );
and then when you write back, they will be saved in that uint8 datatype internally.
To read samples in the original format, add the 'native' option:
[samples, Fs] = wavread('YourFile.wav', 'native');
If they are indeed int16 format then:
samples8 = uint8((double(samples) / 32768 + 1)/2 * 255);
which can be written as
samples8 = uint8( (double(samples)/65536+1/2) * 255);

Steven Lord
Steven Lord 2016 年 10 月 17 日
If you want to convert the values from the int16 or int32 array into uint8, use the uint8 function. Values in the original array that are too small or too large to be stored in uint8 will saturate at intmin('uint8') or intmax('uint8') respectively.
x = int16([-5 20 200 3000])
saturation = [intmin('uint8') intmax('uint8')]
y = uint8(x)
If you want to convert the bit patterns from the original array, use the typecast function. [You may also need or want to use the swapbytes function.]
z = typecast(x, 'uint8')

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by