Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - How to convert float to uint by float representation?

In C I will do this to convert float representation of number into DWORD. Take the value from the address and cast the content to DWORD.

dwordVal = *(DWORD*)&floatVal;

So for example 44.54321 will become 0x42322C3F.

How can I do the same in C#?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the BitConverter class:

uint value = BitConverter.ToUInt32(BitConverter.GetBytes(44.54321F), 0);
Console.WriteLine("{0:x}", value); // 42322c3f

You could also do this more directly using an unsafe context:

float floatVal = 44.54321F;
uint value;
unsafe { 
    value = *((uint*)(&floatVal));
}
Console.WriteLine("{0:x}", value); // 42322c3f

However, I'd strongly recommend avoiding this. See Should you use pointers (unsafe code) in C#?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...