Search code examples
ccodeci2ctwos-complement

2`s complement in 3.13 format(The range is from -4~3.99) what does it mean?


I am using a Relatek audio codec ALC5621 for some custom audio processing application.I use i2c bit banging to control communication between the codec and an soc(cc1110). While figuring out the equalizer part I bumped into a problem, which is stated as follows---> A 16 bit register accepting binary input whose format is --->" 2`s complement in 3.13 format(The range is from -4~3.99) " Register size 16 bit (15,0) ,how can I give data into this register for eg:-4,-1 etc?


Solution

  • 3.13 format represented in Binary Fixed-point arithmetic Notation called "Q" number format.
    Refer to: Fixed-point arithmetic
    3.13 describes a number with 3 integer bit and 13 fractional bits stored as a 16-bit 2's complement integer (quoting Wikipedia).
    Converting a value fixed point value given in Q3.13 to "physical" floating point value is done by dividing the integer value by 2^13.
    The 16 bits integer can be represented as short C variable: short q;
    The "physical" (i.e voltage) value can be represented as double C variable: double v;

    short q; //Q3.13 integer format.
    double v; //"physical" value (assuming voltage).
    

    Converting q to v:

    v = (double)q/(double)(1<<13);
    

    Converting v to q:

    q = (short)floor(v*(double)(1<<13) + 0.5); //Add 0.5 for rounding - round(x) = floor(x+0.5)
    

    Examples:

    q = -32768; //Minimum short range
    //v = -32768 / 8192 = -4.0
    
    q = 32767; //Maximum short range
    //v = 32767 / 8192 = 3.9998779
    
    v = -4.0;
    //q = floor(-4.0*8192.0 + 0.5) = -32768
    
    v = -1.0;
    //q = floor(-1.0*8192.0 + 0.5) = -8192