Connecting Tech Pros Worldwide Help | Site Map

Suggestions on casting needed

Active8
Guest
 
Posts: n/a
#1: Jul 23 '05
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 )[i] > _ymax ) _ymax = ( (short*)buf )[i];
if( ( (short*)buf )[i] < _ymin ) _ymin = ( (short*)buf )[i];
}

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.
--
Best Regards,
Mike
David White
Guest
 
Posts: n/a
#2: Jul 23 '05

re: Suggestions on casting needed


"Active8" <reply2group@ndbbm.net> wrote in message
news:vyhmsuttylf9$.dlg@ID-222894.news.individual.net...[color=blue]
> 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.[/color]

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

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



Closed Thread