Toyo
Toyo

Reputation: 751

Converting data from 8 bits to 12 bits

I am getting signal that is stored as a buffer of char data (8 bits). I am also getting the same signal plus 24 dB and my boss told me that it should be possible to reconstruct from those two buffers, one (which will be used as output) that will be stored as 12 bits. I would like to know the mathematical operation that can do that and why choosing +24dB. Thanks (I am dumb ><).

Upvotes: 0

Views: 2050

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89221

From the problem statement, I guess you have an analog signal which are sampled at two amlitudes. Both signals has a resolution of 8 bits, but one is shifted and truncated.

You could get a 12 bit signal by combining the upper 4 bits of the first signal, and concatenating them with the second signal.

sOut = ((sIn1 & 0xF0) << 4) | sIn2

If you want to get a little better accuracy, you could try to calculate an average over the common bits of the two signals. Normally, the lower 4 bits of the first signal should be approximately equal to the upper 4 bits of the second signal. Due to rounding-errors or noise, the values could be slightly different. One of the values could even have overflowed, and moved to the other end of the range.

int Combine(byte sIn1, byte sIn2)
{
    int a = sIn1 >> 4; // Upper 4 bits
    int b1 = sIn1 & 0x0F; // Common middle 4 bits
    int b2 = sIn2 >> 4;  // Common middle 4 bits
    int c = sIn2 & 0x0F; // Lower 4 bits

    int b;

    if (b1 >= 12 && b2 < 4)
    {
        // Assume b2 has overflowed, and wrapped around to a smaller value.
        // We need to add 16 to it to compensate the average.
        b = (b1 + b2 + 16)/2;
    }
    else if (b1 < 4 && b2 >= 12)
    {
        // Assume b2 has underflowed, and wrapped around to a larger value.
        // We need to subtract 16 from it to compensate the average.
        b = (b1 + b2 - 16)/2;
    }
    else
    {
        // Neither or both has overflowed. Just take the average.
        b = (b1 + b2)/2;
    }

    // Construct the combined signal.
    return a * 256 + b * 16 + c;
}

When I tested this, it reproduced the signal accurately more often than the first formula.

Upvotes: 1

Related Questions