Home > database >  casting int32_t to std::complex<float>
casting int32_t to std::complex<float>

Time:12-29

I receive some data over a wire protocol. One of the packets I receive has some int32_t values that represent complex numbers. i.e. 10 complex numbers come in the form of 20 int32_t values (real,imag).

I need to convert the int32_t's to float's and copy these values into a vector<std::complex<float>>. I am not sure of the preferred method to do this.

this works but sure is ugly and highly questionable. This is a sudo realtime system and I need as fast an operation as possible.

float coefBuffer[20];
std::transform(packet.coef,packet.coef 20,coefBuffer, [](int32_t x) { return (float)x;});
std::memcpy(complexFloatVector.data(),coefBuffer,sizeof(float)*20);

I tried many kinds of casting and could not come up with a better solution.

Any suggestions appreciated.

CodePudding user response:

What about:

for ( uint32_t j=0; j<10;   j ) {
    complexFloatVector[j] = std::complex<float>(packet.coef[2*j],packet.coef[2*j 1]);
}

CodePudding user response:

Don't overthink it

complexFloatVector.resize(10);
for (size_t i = 0; i < 10; i  )
{
    complexFloatVector[i] = std::complex<float>((float)(packet.coef[i * 2]), (float)(packet.coef[i * 2   1]));
}

I'm assuming complexFloatVector is a std::vector<std::complex<float>> type and packet.coef is an array of 20 integers.

  • Related