M
M
Michael2015-01-31 22:12:02
Programming
Michael, 2015-01-31 22:12:02

How to correctly convert information from byte to int?

Hello. I am writing a program for processing sound from a microphone. The data is stored in a char array. One report is equal to 16 bits. Advise how to competently convert this data to int in order to build an amplitude graph based on it.
I get the reports from the microphone using the bass.dll library function

rchan = BASS_RecordStart(FREQ,CHANS,0,&DuffRecording,0);  // rchan - канал записи

and its callback:
BOOL CALLBACK DuffRecording(HRECORD hangle, const void *buffer, DWORD lenght, void *user)
  {
  if((reclen % BUFSTEP) + lenght >= BUFSTEP)  // динамическое выделение памяти под поток
  recbuf = (char *)realloc(recbuf,((reclen + lenght) / BUFSTEP + 1) * BUFSTEP);
  memcpy(recbuf+reclen,buffer,lenght);  // recbuf - массив отчетов char, из которого мне необходимо извлечь и обработать данные
  reclen+=lenght;  // reclen - длина массива recbuf 
  return TRUE;
  }

The stream stores microphone reports in a char recbuf array. 2 bytes - one report. I need to work with them somehow.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jcmvbkbc, 2015-02-02
@mmisin1

Kapets was advised.
Assuming your machine has the same endianness as the data, I would do this:
char *recbuf = ...; // <-- input data
int16_t *samples = (int16_t*)recbuf; // <-- they are the same, in the form of signed 16-bit numbers.
Everything. Refer to samples.

T
tsarevfs, 2015-01-31
@tsarevfs

You can just loop through:

std::vector<char> data = get_data();
std::vector<int> data2plot;
for (int i  = 0; i < data.size() / 2; ++i)
{
  int hi = data[2 * i];
  int lo = data[2 * i + 1];
  data2plot.push_back((hi << 8) | lo);
}
plot(data2plot);

G
GavriKos, 2015-01-31
@GavriKos

Duc and build a graph in char, what's the problem, why convert?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question