Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 655
Pablo Avatar asked Feb 15 '14 17:02

Pablo


People also ask

Can you convert a float to an int?

Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.

How do you convert a float to a whole number?

Method 1: Conversion using int(): To convert a float value to int we make use of the built-in int() function, this function trims the values after the decimal point and returns only the integer/whole number part.

Can we convert float to int in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 .

How do you convert floating to int and rounding?

round() method, which converts float to its nearest integer by adding +0.5 to it's value and then truncating it.


2 Answers

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#?

like image 199
p.s.w.g Avatar answered Oct 10 '22 07:10

p.s.w.g


Use the BitConverter class:

float f = 44.54321f;
uint u = BitConverter.ToUInt32(BitConverter.GetBytes(f), 0);
System.Diagnostics.Debug.Assert(u == 0x42322C3F);
like image 24
Hans Passant Avatar answered Oct 10 '22 09:10

Hans Passant