P Cresswell
P Cresswell

Reputation: 51

Is there an elegant way to convert vector<complex<float>> to vector<short>?

My class is receiving a vector of complex floats, but the data stream packets must have the data as short. My solution is to first convert the data to short, then batch it into the packets, and send them. What would be the best method of converting this data?

The complex data should map to two separate variables: for example, vcfSampleData[0].real() -> m_pData[0], and vcfSampleData[0].imag() -> m_pData[1] and so on.

void BufferSampleData(const std::vector<std::complex<float>>& vcfSampleData, const float& fTotalGain_dB, const Frequency& CentreFrequency, const Bandwidth& cBandwidth, const TimeStamp& tCaptureTime, const SampleRate& SampleRate)
{
    sBufferData* pWriteElement = m_SampleBuffer.GetWriteElement();
    if(pWriteElement != nullptr) {
        std::copy(vcfSampleData.begin(), vcfSampleData.end(), pWriteElement->m_pData); //vector<comlex<float>> must become vector<complex<short>> or vector<short>
        //other irrelevant stuff here
        m_SampleBuffer.CommitWriteElement();
    }
}

Upvotes: 1

Views: 1312

Answers (2)

Caleth
Caleth

Reputation: 62686

There isn't a std:: function that does what you are asking for, you'll just have to write a loop

pWriteElement->m_pData.reserve(vcfSampleData.size() * 2);
pWriteElement->m_pData.clear();
for (auto cmpl : vcfSampleData)
{
    pWriteElement->m_pData.push_back(cmpl.real());
    pWriteElement->m_pData.push_back(cmpl.imag());
}

Upvotes: 1

user31264
user31264

Reputation: 6727

KISS.

void Transform (const std::vector<std::complex<float>>& vSrc, const std::vector<short>& vDst) {
    vDst.resize(2*vSrc.size());
    for (std::size_t i=0; i<vSrc.size(); i++) {
        vDst[2*i] = vSrc[i].real;
        vDst[2*i+1] = vSrc[i].imag;
    }
}

Upvotes: 0

Related Questions