byte -> short -> byte そしてfloat(Objective-C)

プロフェッショナルプログラマーと同じ内容です。

こんにちは信号処理とデバイスまわりでのデータ移動のために必要なものを実装しておきました。iOS, Mac OS で活用できると思います。
何に使うかといえば特に音声系です。

Byte Low Level APIでの扱い
short(Int16) 16bitのデータ, 音声系は16bit, 32b it系が多いのでしょうか
float FFT等の信号処理のライブラリはfloat, doubleが多いのでこれらの変換も必要

これらの値をさくっと変換して計算に活用したいというのが今回の目的です
short はだいたいの処理系で16bitでしょうか。わかりやすくするためObjective-CのInt16を使いましょう。

もう少しByte, short について。  このプログラムは 2 byteのデータを1つのshort(Int16) に変換するものです

Sample

  • Byte配列 -> short(Int16)
  • short(Int16) -> Byte配列
  • short(Int16) -> float
  • float -> short(Int16)

byte配列 -> short(Int16)

+(SInt16)convertByteToShort:(Byte *)bytes order:(BOOL)order
{
    if ( order )
    {
        // Small address first
        SInt16 res = (bytes[0] << 8) + bytes&#91;1&#93;;
        return res;
    }
    else
    {
        SInt16 res = (bytes&#91;1&#93; << 8) + bytes&#91;0&#93;;
        return res;
    }
}
&#91;/cpp&#93;

※エンディアン系の処理のためちょっと変則的なコードになっています

<h4>short(Int16) -> byte配列</h4>
[cpp]
+(void)convert16ToByte:(SInt16)src bytes:(Byte *)bytes order:(BOOL)order
{
    if ( order )
    {
        bytes[0] = (src & 0xFF00) >> 8;  // Big Endian
        bytes[1] = (src & 0xFF);
    }
    else
    {
        // Small address first
        bytes[1] = (src & 0xFF00) >> 8;  // Little Endian
        bytes[0] = (src & 0xFF);
    }
}

short(Int16) -> float

+(float)getNormarilize16Bit:(SInt16)signal
{
    return (float)signal / (float)32768;
}

float -> short(Int16)

+(SInt16)restore16Bit:(float)signal
{
    return (SInt16)(signal * 32768);
}