I am reading data from an energy meter over modbus protocol and I am getting hex values from there. I want to convert that hex string to floating point value. For example - 0x416f0000 denotes a value of 14.9375.Reference
Can anyone please help me how to do it on Arduino IDE?
-
You mean Modbus ASCII, right? Non-ASCII Modbus doesn't use hex.Edgar Bonet– Edgar Bonet2018年12月11日 10:32:47 +00:00Commented Dec 11, 2018 at 10:32
1 Answer 1
If you do indeed have an ASCII string of hexadecimal numbers (and not a raw binary float), then your best option may be to do the conversion in two steps:
- convert the string to a 32 bit unsigned number using
strtoul()
- reinterpret the binary pattern of this integer as a float.
For example, the following program:
void setup() {
const char modbus_data[] = "416F0000";
union {
uint32_t i;
float f;
} data;
data.i = strtoul(modbus_data, NULL, 16);
Serial.begin(9600);
Serial.println(data.f, 4);
}
void loop(){}
prints 14.9375
.
Note that for strtoul()
to function properly, the hex string must be
followed by a character that is not a valid hex digit (a 0円
in the
example above).