Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion from unsigned int to float

warning C4244: '=' : conversion from 'unsigned int' to 'float', possible loss of data  

Shouldn't a float be able to handle any value from an int?

unsigned int: 0 to 4,294,967,295  
float 3.4E +/- 38 (7 digits) 

Wiki:

The advantage of floating-point representation over fixed-point (and

integer) representation is that it can support a much wider range of values.

Any insight would be helpful, thanks.

http://msdn.microsoft.com/en-us/library/s3f49ktz%28VS.80%29.aspx

like image 320
T.T.T. Avatar asked Aug 04 '10 00:08

T.T.T.


People also ask

How do you convert int to float?

To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00.

Is unsigned int a float?

'unsigned int' and 'float' both use 32 bits to store values. Since a float has a larger range, it necessarily sacrifices some precision. This means that there are some unsigned int values that cannot be accurately represented in a float.

How do I turn an unsigned int into a string?

The utoa() function coverts the unsigned integer n into a character string. The string is placed in the buffer passed, which must be large enough to hold the output. The radix values can be OCTAL, DECIMAL, or HEX.

How do I convert unsigned to signed int?

To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.


2 Answers

'unsigned int' and 'float' both use 32 bits to store values. Since a float has a larger range, it necessarily sacrifices some precision. This means that there are some unsigned int values that cannot be accurately represented in a float. MSDN provides some more details.

like image 197
JaredReisinger Avatar answered Oct 06 '22 00:10

JaredReisinger


While float supports a wider range of values than unsigned int, it does so with less accuracy. Floats have a 23-bit mantissa which, as you posted, is only about 7 decimal digits. unsigned ints support over 9 decimal digits.

Suggestion: use double, not float.

Edit: Actually, I retract that suggestion; floating-point and integer data types are fundamentally different and are not directly convertible. What integer value do you expect to get for Single.MaxValue? For Single.NegativeInfinity? Explaining why you want to convert from float to int would be helpful.

like image 27
Dour High Arch Avatar answered Oct 05 '22 23:10

Dour High Arch