473,839 Members | 1,538 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to convert float to unsigned int

1 New Member
when you convert 1.7 to unsigned int, it becomes 1 or 2?
Jan 15 '13 #1
9 64101
weaknessforcats
9,208 Recognized Expert Moderator Expert
You can't convert a float to an int. An int has no decimal portion so part of your float value gets lost.

Your compiler will warn you about this. If you ignore the warning then any bad things that happen later will not be the compiler's fault.

You can however convert an int to a float with a zero decimal portion. But you can't convert it back.

And typecasting a float to an int just chops off the decimal portion and any bad things that happen later will be the fault of this cast and not the fault of the compiler.
Jan 15 '13 #2
gorav sharma
2 New Member
typecasting is not possible from float to unsigned int
Jan 15 '13 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
Try this:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    float x = -1.0;
  4.   unsigned int y;
  5.   y = (unsigned int) x;
  6.  
  7. }
The whole point of a cast is to tell the compiler to not follow the rules and to just do what you say, however incorrect.

In the above code, y becomes 4294967295 but what can I say. The cast absolves the compiler from doing things correctly.
Jan 15 '13 #4
Anas Mosaad
185 New Member
@Mr. Digits: Casting 1.7 to unsigned int becomes 1. However, you may round or ceil by including <math.h>

@WeaknessforCat s: It's totally dependent on the underlying binary representation of the number being cast. For example, casting -1 to unsigned gets 4294967295.

However, If we understand the binary representation of the number, you won't get surprised with this result. Negative numbers are represented in the two's complement form which makes it logical to get 4294967295 for -1 when dealing with it as unsigned.

For the floating point, it's another story where the binary representation has some specific bits for the sign, exponent and mantissa.
Jan 15 '13 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
All you are telling me is that when you cast the results of the cast are indeterminate. That is, the type safety of your program has been lost. It doesn't matter what is the result of the cast.

Cast errors in C are one of the biggest reasons C++ was created.
Jan 15 '13 #6
donbock
2,426 Recognized Expert Top Contributor
(I'm on the road so I can't test this on a real compiler. Let me know if I'm wrong.)

An implicit conversion is associated with the assignment operator (ref C99 Standard 6.5.16). The C99 Standard goes on to say:
6.3.1.4 Real floating and integer
1 When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.
If the destination is an unsigned int then the behavior is defined as long as the integral part of the floating value is nonnegative and can fit in an unsigned int.

Thus, the following code snippet ought to compile without errors and yield this output: "1 + 3".
Expand|Select|Wrap|Line Numbers
  1. void sub(void) {
  2.   float f = 1.5f;
  3.   double d = 3.14159265358;
  4.   unsigned int i, j;
  5.   i = f;
  6.   j = d;
  7.   printf("%u + %u\n", i, j);
  8.   }
That's not the end of the story. C99 introduced new header <fenv.h>. This header provides the fesetround() function which allows you to change the floating point rounding behavior. Options may include:
  • FE_DOWNWARD (same as the floor function)
  • FE_UPWARD (same as the ceil function)
  • FE_TONEAREST (same as the round function)
  • FE_TOWARDZERO (same as the trunc function, and 6.3.1.4)
Much of the <fenv.h> capabilities are implementation-dependent. Macros for unsupported rounding behavior are not defined. Be very careful how you try to use this capability.

I wouldn't use <fenv.h> -- it isn't portable. Portable methods to achieve these rounding behaviors are:
Expand|Select|Wrap|Line Numbers
  1. #include <math.h>
  2.    float f;
  3.    unsigned int u;
  4.    u = floor(f);   // FE_DOWNWARD
  5.    u = ceil(f);    // FE_UPWARD
  6.    u = round(f);   // FE_TONEAREST
  7.    u = trunc(f);   // FE_TOWARDZERO
  8.    u = f;          // FE_TOWARDZERO
Jan 15 '13 #7
weaknessforcats
9,208 Recognized Expert Moderator Expert
All true but I was speaking strictly of a typecast.
Jan 16 '13 #8
donbock
2,426 Recognized Expert Top Contributor
An explicit conversion (cast) should work the same as an implicit conversion (no cast).
Expand|Select|Wrap|Line Numbers
  1. unsigned int i, j; 
  2. i = (unsigned int) 1.5f; 
  3. j = 3.14159265358; 
  4. printf("%u + %u\n", i, j);   // output: "1 + 3"
Your earlier example illustrates undefined behavior due to assigning a value outside the range of the destination type. The following assignments trigger undefined behavior because we're trying to assign a negative value to an unsigned type, not from converting floating point to integer.
Expand|Select|Wrap|Line Numbers
  1. unsigned int a, b, c;
  2. a = (unsigned int) -1.5f;
  3. b = (unsigned int) -1.8;
  4. c = (unsigned int) -1;
The asserts in the following snippet ought to prevent any undefined behavior from occurring.
Expand|Select|Wrap|Line Numbers
  1. #include <limits.h>
  2. #include <math.h>
  3. unsigned int convertFloatingPoint(double v) {
  4.    double d;
  5.    assert(isfinite(v));
  6.    d = trunc(v);
  7.    assert((d>=0.0) && (d<=(double)UINT_MAX));
  8.    return (unsigned int)d;
  9.    }
Jan 16 '13 #9
weaknessforcats
9,208 Recognized Expert Moderator Expert
The point I am trying to make is that with a cast you cannot guarantee correct results using the rules of the language.

True an unsigned int has no sign bit but the cast tells the compiler that I don't really care. I know more about this program than you do and I personally guarantee only unsigned int values in that float. So forget language rules and just do what I tell you.

A correctly designed program does not have these indeterminate results kinds of behavior.

By the time you get to C++, a cast means a)I am using C code with void* or b) my design is screwed up.
Jan 16 '13 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
23177
by: jaijai_kumar | last post by:
Select Cast('100.1234' as float) give me the result 100.1234 Now when I convert it back to char I want exactly 100.1234 Select Convert(char(100),Cast('100.1234' as float)) Gives me 100.123 (Here I was expecting 100.1234) When I do Select STR(Cast('100.1234' as float),25,4) I get back the result as 100.1234
2
32339
by: Goran | last post by:
Hi! I need to convert from a unsigned char array to a float. I don't think i get the right results in the program below. unsigned char array1 = { 0xde, 0xc2, 0x44, 0x23}; //I'm not sure in what order the data is stored so i try both ways. unsigned char array2 = { 0x23, 0x44, 0xc2, 0xde}; float *pfloat1, *pfloat2;
9
90551
by: FalkoG | last post by:
Hello colleague I want to convert a floating number for example 5236.9856982 to a hexadecimal number. I'd tried several things but my problem is to convert the position after decimal point. I searched numberless websites but nothing could answer my question. I would be pleased to get some help. Regards
1
2895
by: vsk | last post by:
Hai, I need to know how to convert an unsigned char array into hexstring. can anyone help me in this regard?. Thanks.
1
17000
by: War Eagle | last post by:
Is it possible to convert an unsigned long to byte array. For instance, unsigned long = 23480923 unsigned long longNumber; longNumber=23480923; // in binary = 1 0110 0110 0100 1010 0101 1011 // so i want byteArray=0000 0001 , byteArray=0110 0110 , // byteArray=0100 1010, byteArray=0101 1011. Is there a way to get the 4 bytes that make up this variable? Also, is there a way to take a 4 byte array and convert it into a long?
4
25107
by: Pixie Songbook | last post by:
Hi, I'm trying to write a program using the Dev C++ 4.9.9.2 compiler that takes input numbers from a word document, sums them together, and then gives me a result. It should be easy as the book I have tells me what to do, problem is I get the error message "cannot convert `float' to `float*' for argument `1' to `float array_sum(float*, int)' " for line 22 of the program. This is what I have; #include <iostream.h> #include <fstream.h> ...
2
6903
by: lisasahu | last post by:
how to convert float to string like there is atof atoi and itoa but is ther any method to convert float to string
5
3328
by: sidhuasp | last post by:
Hi could anyone please tell me how to convert float value in my database ti HOUR/MIN format for my timesheet requirement. i have to do it in sql-reporting services
2
817
by: ireyes | last post by:
DEAR SIR, I SAW YOUR INTERNET QUESTION AND I HAVE THE SAME TROUBLE. CUOLD YOU HELP ME TO MAKE A FLOAT TO INTEGER CONVERTION? DO YOU HAVE ANY EXEL FILE THAT CAN DO THAT? REGARDS AND THANKS A LOT IVAN REYES ___________________________________
9
5128
by: tvnaidu | last post by:
I am doing floating point calculation inside C function, with debugger I can see float values in single step, if I want to print them on console, I am using printf, but printf not working for flaot, how can I convert them to int and print on console using printf. I tried to print with %d, but float, but not printing, any idea?. Thanks.
0
9855
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10585
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10647
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9426
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7828
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7017
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5866
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4064
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3132
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.