Char array to qint24 array
-
I'm doing music processing on 24bit samples. The raw samples are stored in a char array. I want to convert this array to a qint24 array.
Now since there is no qint24 type, I decided to use qint32. A char has a size of 1 byte, so I will have to convert 3 chars to a 24bit sample at a time and store it in a qint32. This is what I'm currently doing:
Code:
@char temp[3];
int bufferCurrent;
for(int i = 0; i < size; ++i)
{
bufferCurrent = i * 3;
temp[0] = buffer[bufferCurrent];
temp[1] = buffer[bufferCurrent + 1];
temp[2] = buffer[bufferCurrent + 2];
result[i] = reinterpret_cast<qint32>(temp);
}@buffer is the char array and result my new array for the 24bit samples. g++ complaints that it can't convert char* to qint32 (loses precision).
So I basically need some way to convert 3 chars to a qint32. Any ideas of how to accomplish this?
-
You could try playing with shifts
@
char temp[3];
int bufferCurrent = 0;
for(int i = 0; i < size; i++)
{
int intermediate = (int)buffer[bufferCurrent];
intermediate |= ((int)buffer[bufferCurrent + 1]) << 8;
intermediate |= ((int)buffer[bufferCurrent + 2]) << 16;
result[i] = intermediate;
bufferCurrent += 3;
}
@or the following depending on the endianness of the message:
@
char temp[3];
int bufferCurrent = 0;
for(int i = 0; i < size; i++)
{
int intermediate = (int)buffer[bufferCurrent+2];
intermediate |= ((int)buffer[bufferCurrent + 1]) << 8;
intermediate |= ((int)buffer[bufferCurrent]) << 16;
result[i] = intermediate;
bufferCurrent += 3;
}
@ -
Thanks. I assume << 8 and << 16 determines where the corresponding value will be placed in bytes (eg: starting at bit 8 or bit 16).
-
Hello
In fact << 8 and << 16 mean "bit shifts":http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts. -
If you want to reinterpret to a 32 bit type, you need 32bits in the beginning. So temp should be an array of four bytes with the high byte set to 0, not 3 bytes (24 bits).
Also, be aware of endianess issues - it depends on the CPU architecture whether the most significant byte is at index 0 or at index 3.