문제

I copy the following 4 bytes: 0x40, 0x7E, 0xA7, 0xF2 to a float variable using memcpy. Now my c compiler reserves 4 bytes for a float, so the 4 bytes I copy into it should not cause overflow.

My output for "Current" is -2147483648-2147483648.-2147483648 mA.

The value -2147483648 seems to suggest buffer overflow. I am not sure why it gives me this value. Here is a compiled example:

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

typedef struct {
  float     current;
} hart_value_t;
hart_value_t  hart_values;

unsigned char buf[4] = { 0x40, 0x7E, 0xA7, 0xF2 };

void spltfp(double value, int * intpart, int * decpart)
{
  int i;
  double dec;

  i = (int)value;
  printf("What value do I get here: %d", i);
  dec = value - i;

  if (dec < 0) {
    dec = -dec;
  }

  *intpart = i;
  *decpart = (int)(dec * 100);
}

void hartBufferReadFloat(unsigned char * buf, float * data)
{
  printf("What is the size of float: %lu", sizeof(float)); // returns 4
  memcpy(data, buf, 4); /* 0x40, 0x7E, 0xA7, 0xF2 */
}

void hartPrintFloat(float val)
{
  int intpart, decpart;

  spltfp(val, &intpart, &decpart);
  printf("%d.%02d", intpart, decpart);
}

int main(void)
{
    hartBufferReadFloat(buf, &hart_values.current);
    printf("Current: "); hartPrintFloat(hart_values.current); printf(" mA\n");
    return 0;
}
도움이 되었습니까?

해결책

You have the values, 0x40, 0x7e, 0xa7, 0xf2, in the order for a big-endian system, but your system is little-endian. They need to be reversed.

Directly accessing the bytes that represent objects is generally not portable between different systems. The order in which bytes appear in the representation is just one of the differences that may occur.

다른 팁

The float has it own format, where not all int-like 32 bit values are valid. Check IEEE 754

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