Domanda

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;
}
È stato utile?

Soluzione

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.

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top