I'm going to convert a C# floating point number into 2 bytes, for instance I have number 12.4544 and it should be 0x4147, or 0x41474539, I've used bitconverter.doubletoInt64, but it gives me something weird, how can I get 0x4147?
I'm creating a MODBUS slave, and I should send each float number as only 2 bytes
thanks
EDIT: Oh dear oh dear, I completely missed this, which is the short answer:
Use BitConverter.GetBytes
and pass it a float, as shown here.
The long answer:
BitConverter doesn't support single precision floats, just double
s. You'll have to create a C# "union", like so:
[StructLayout(LayoutKind.Explicit)]
class Floater
{
[FieldOffset(0)]
public float theFloat;
[FieldOffset(0)]
public int theInt;
}
Put your float in theFloat
and look at theInt
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.