I try to write a function that takes two bytes and converts them to a float. My function takes short_buffer, which is an array of signed chars, converts each two adjacent values in it to a float, and then put it in data_float. This function works only if the float values are positive (only for unsigned chars), and for negative values I get a wrong answer, I guess it because of an overflow.
How can I fix it so that it will work for negative floats as well?
Here is my code:
void short_2_float( char* short_buffer, int size_of_short_buffer, float* data_float )
{
int data_in_channel =0;
for(int i = 0, k=0; i < size_of_short_buffer ; i+=2, k++)
{
data_in_channel = (short_buffer[i] & 0x00ff) | (short_buffer[i + 1] << 8);
data_float[k] = (float)data_in_channel / 32768.0;
}
}
Example for results I got:
short_buffer[0]= 14, short_buffer [1] = 0 real data_float[0] value = 0.000427, my data_float[0] value = 0.000427
short_buffer[2] = 209, short_buffer [3] = 252 real data_float[1] value = -0.024872, my data_float[1] value = 1.975128
Thanks in advance
question from:https://stackoverflow.com/questions/65648467/convert-from-two-bytes-to-a-float