我想将浮点数转换为两个16位整数。
我编写的代码如下:
float floatCurrentVolume = 1234.50;
uint32_t ui32TemperaryVariable1;
uint16_t ui8ModbusRegister[2] = {0};
ui32TemperaryVariable2 =(uint32_t ) floatCurrentVolume;
ui8ModbusRegister[0] = (uint16_t )(floatCurrentVolume && 0x0000FFFF);
ui8ModbusRegister[1] = (uint16_t )((ui32TemperaryVariable3 >> 16) && 0x0000FFFF);
基本上,floatCurrentVolume应该分为两个16位寄存器。
但是,当我检查输出时,我得到ui8ModbusRegister [0] = 0,ui8ModbusRegister [1] = 1。
代码有什么问题??
最佳答案
您有错误的&&
和&
字符用例。第一种情况是逻辑AND,结果将是1
或0
,而第二种情况是按位AND,这就是您要查找的内容。
ui8ModbusRegister[0] = (uint16_t )(floatCurrentVolume && 0x0000FFFF);
ui8ModbusRegister[1] = (uint16_t )((ui32TemperaryVariable3 >> 16) && 0x0000FFFF);
应该
// |--here
ui8ModbusRegister[0] = (uint16_t )(floatCurrentVolume & 0x0000FFFF);
ui8ModbusRegister[1] = (uint16_t )((ui32TemperaryVariable3 >> 16) & 0x0000FFFF);
// |--here
如果要真正发送整个浮点数(包括小数),则必须复制内存,如下所示:
//Copy float to modbus register
memcpy(ui8ModbusRegister, &floatCurrentVolume, sizeof floatCUrrentVolume);
//And then on receive side, copy it back before read
memcpy(&floatCurrentVolume, ui8ModbusRegister, sizeof floatCUrrentVolume);
关于c - 浮点数转换为C中的两个16位整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44585932/