简体   繁体   中英

Convert 4 bytes into 32-bit Float in CAPL?

I Want to convert a CAN Message(4Bytes) into a Float value.

I'm reading a value from the current sensor and convert into 4 bytes send them using CAN Shield to Vector CANoe.In the Arduino program, converted the float value into bytes and back again is possible using Unions. In CAPL, I Can't use unions & pointers.

Arduino code:

unsigned char arr[4] = {0,0,0,0};

typedef union
{
 float number;
 uint8_t bytes[4];
} floatunion;

floatunion myFloat;

myFloat.number = lowAmps; // Assign a converted current value to the float

lowRawValue = AvgSnsrData[0]; //Input Sensor Data
lowVoltage = (lowRawValue / 1024.0) * 5000; // Gets you mV
lowAmps = ((lowVoltage - ACoffset) / mVperAmp);

for (int i=0; i<4; i++)
{
     Serial.print(myFloat.bytes[i], HEX); // Print the hex representation of the float
     Serial.print(' ');
     arr[i] = myFloat.bytes[i]; //Save in unsigned char array 
}
I've tried a few from web(https://stackoverflow.com/questions/52590435/capl-converting-4-raw-bytes-into-floating-point) but nothing works well.

Also tried:

float test = (myFloat.bytes[3]<<24|myFloat.bytes[2]<<16|myFloat.bytes[1]<<8|myFloat.bytes[0]<<0);

Is there is anyway to convert this without using union or pointer in CAPL/C? Any builtin function in CAPL?

Thanks in Advance.

To convert raw byte into float value you can use following build in functions :

float interpretAsFloat(dword x); // dword 4 bytes, IEEE signle precision float number
double interpretAsDouble(qword x); // qword 8 bytes, IEEE double precision float number

Examples:

on key 'a'
{
 dword testDword=0x4048f5c3; // 3.14
 float testFloat;
 testFloat=interpretAsFloat(testDword);

 write("float  %f",testFloat);
 write("float times two  %f",testFloat*2);
}




on message ExampleCANMessage
{
  float lowAmps;

  lowAmps=interpretAsFloat(this.dword(2));// ex. your data is present on bytes 2...5 
  print("Voltage: %f ",lowAmps);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM