Reputation: 3279
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
Upvotes: 0
Views: 922
Reputation: 39023
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
Upvotes: 4