# How to covert int32 or int16 to uint8?

156 ビュー (過去 30 日間)
Hassan Iqbal 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 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
samples8 = uint8( (samples + 1)/2 * 255 );
and then when you write back, they will be saved in that uint8 datatype internally.
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 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

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')

サインインしてコメントする。

### カテゴリ

Find more on Logical in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by