문제

I am reading characters over a rs-232 serial line from a meter. Due to the check sum byte being correct, I am 100 percent sure the values are all correct. One thing that confuses me is that 4 bytes that represent a pressure value returns -0.000000. That negative sign doesn't seem right at all. Here's an extracted example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

unsigned char cmd[] = {
    0x80, 0x00, 0x00, 0x00
};

float float_byte_join(unsigned char *from, int size)
{
    float value;
    value = 0;
    unsigned char * p = (unsigned char *)&value;
    int i, j;

    for (i = 0, j = size - 1; i < size; i++, j--) {
        p[j] = *from;
        ++from;
    }
        printf("value is %f\n", value);
    return value;
}

int main(void)
{
  float_byte_join(cmd, 4);
  return 0;
}

// result:
value is -0.000000

Any idea why this prints -0.000000 rather than 0.000000? Do those 4 characters really represent a negative number? I thought two's complement has no such thing as a negative 0.

도움이 되었습니까?

해결책

Two's complement integers have no negative zero, but IEEE floating point values do have a negative zero, and it is encoded as 80 00 00 00 (hex, big-endian, single-precision). So if that really is the byte sequence you are getting from your device, then that is the correct result.

This and many other oddities of IEEE floating point are explained and justified in the paper What Every Computer Scientist Should Know About Floating Point, which, since you are a computer scientist, you should read.

다른 팁

You set the sign bit( most significant bit ) to 1 which specifies a negative number, change it to 0.

unsigned char cmd[] = {
0x00, 0x00, 0x00, 0x00
};

(but anyway: -0.0f == 0.0f )

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top