Suggestions on casting needed

A

Active8

Something's wrong and I think it's my pointer arithmetic. I'm
reading from the soundcard, so the buffer is pointed to by char*
Maybe the last time I did this it was with BYTE*

For 16 bit stereo, the first short (signed word) is the first sample
of the left channel, the second short is the first right channel
sample.

If I cast the pointer to this char buffer to short* will buf[0],
buf[1], ... give me the first and second WORD samples, or will it be
wrong? Here's one relevant snip I'm not sure of.

for(int i=0;i<nsamps/2;i++)
{
if( ( (short*)buf ) > _ymax ) _ymax = ( (short*)buf );
if( ( (short*)buf ) < _ymin ) _ymin = ( (short*)buf );
}

I suspect the fact that nsamps/2 in the for stmnt works and nsamps
crashes means that the cast is not fixing up the pointer arithmetic.
And I'd need i+=2 for each iteration of the loop. Even doing that
gives the wrong result. _ymax ends up being greater than _ymin, but

_yceiling = ceil(_ymax); // part of scaling calcs for a plot.
_yfloor = floor(_ymin); // it worked for simple bufs with no casting

gives me a ceiling less than the floor. All variables prefixed with
_y are floats, so maybe there's a loss of data (sign?). I can't
think it through.

Maybe someone could suggest how they would deal with this.

Thanks in advance.
 
D

David White

Active8 said:
Something's wrong and I think it's my pointer arithmetic. I'm
reading from the soundcard, so the buffer is pointed to by char*
Maybe the last time I did this it was with BYTE*

For 16 bit stereo, the first short (signed word) is the first sample
of the left channel, the second short is the first right channel
sample.

If I cast the pointer to this char buffer to short* will buf[0],
buf[1], ... give me the first and second WORD samples, or will it be
wrong? Here's one relevant snip I'm not sure of.

Yes, it will give the 16-bit samples if the indexing comes after the cast.
for(int i=0;i<nsamps/2;i++)
{
if( ( (short*)buf ) > _ymax ) _ymax = ( (short*)buf );
if( ( (short*)buf ) < _ymin ) _ymin = ( (short*)buf );


Just remove the /2 from the for loop - assuming that nsamps is the total
number of 16-bit samples. Alternatively, you could cast buf to a short* at
the outset and store it in a short* variable and use that in the loop
without a cast.

DW
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top