Modbus Float to Int

Hi i want to convert a float to int.
The float is createt whit this code:

float num;
unsigned long temp = (unsigned long)regs[0] << 16 | regs[1];
num = *(float*)&temp;

Im not realy familiar whit bitshifting. How create the 2 int values from float?

(deleted)

Something like:

  int regs[2] ;
  unsigned long lng = *(long *)(&num) ;
  regs [0] = (int) (lng >> 16) ;
  regs [1] = (int) (ing & 0xFFFF) ;

works thanks!

I'm not quite sure if I understand; there are already 2 ints (by the looks of it; in the regs); why convert to float and next back to int?

Can't you directly use those values in the regs?

I also have a bit of a doubt about your conversion but I can't pinpoint it. The below code prints OVF for the num variable. The numbers for the regs are based on the original float 123.45.

union X
{
  float f;
  unsigned int i[2];
  unsigned char b[4];
};

void setup()
{
  Serial.begin(115200);

  X x;
  x.f = 123.45;


  // display 123.45 as its components (two ints, 4 bytes)
  Serial.println(x.i[0], HEX);
  Serial.println(x.i[1], HEX);
  Serial.println(x.b[0], HEX);
  Serial.println(x.b[1], HEX);
  Serial.println(x.b[2], HEX);
  Serial.println(x.b[3], HEX);

  int regs[] = {0xE666, 0x42F6};  // represents 123.45

  // make sure it's cleared to prevent possible confusion
  x.i[0] = x.i[1] = 0;
  Serial.println(x.f, 8);   // prints 0.00000000

  // copy the regs to the enum
  x.i[0] = regs[0];
  x.i[1] = regs[1];
  // and check the result
  Serial.println(x.f, 8);   // prints 123.44999694

  float num;
  unsigned long temp = (unsigned long)regs[0] << 16 | regs[1];
  num = *(float*)&temp;
  Serial.println(num, 8);   // prints ovf
}

void loop()
{

}

I need to do this because i have to trasmit float value over serial modbus and read the incoming floats. Modbus has registers of integers, because of that you need to union 2 registers.

I still don't get it; you already have the float as two integers in regs[0] and regs[1]. So why don't you just send the regs?

But OK, probably me and your problem is solved so the case can be closed :wink: