Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

Values larger than 127 in your char array are converted to negative values. So when you do this:

short_buffer[i + 1] << 8

The value in short_buffer is first promoted to int. So for example 252 is converted to -4 when stored (0xfc) which as an int is 0xfffffffc and shifting left by 8 gives you 0xfffffc00 (actually this is undefined behavior because you're left-shifting a negative value).

As mentioned in the comments, if you cast this value to unsigned char before doing anything else it will be converted to the value 252 and the calculation will work.

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) | 
                          ((unsigned char)short_buffer[i + 1] << 8);
        printf("data=%d
", data_in_channel);
        data_float[k] = (float)data_in_channel / 32768.0;

    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...