How to covert int32 or int16 to uint8?
59 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(2 个)
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);
0 个评论
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')
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!