1

I am trying to get a string using a CGFloat, something like this..

helpMessage = [NSString stringWithFormat:@"The unsigned integer value is %i", (unsigned int)myCGFloat];

This does not want to work. Given a CGFloat value of -2 I am getting 0 for in the string.

If I use...

helpMessage = [NSString stringWithFormat:@"The unsigned integer value is %i", (int)myCGFloat];

I get -2. That's getting closer. So I thought I could use @u as the format specifier but I get 4294967294.

What am I doing wrong.

Thanks in advance for any help. This should be an easy one.

John

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
user278859
  • 10,379
  • 12
  • 51
  • 74

3 Answers3

3

You're getting 4294967294 because after converting your value to an unsigned int, there isn't a bit that can be used to represent the negativity of -2, so the value "underflows" by 2 instead, so to speak:

0
4294967295 (-1)
4294967294 (-2)

You should be formatting as a signed integer (%i) if you want to display negative values. The range of a signed 32-bit integer is -2147483648 to 2147483647, while the range of an unsigned 32-bit integer is 0 to 4294967295.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

So you are trying to cast -2 to an unsigned int? Unsigned int's cant be less than 0. It is thus going to be represented incorrectly.

D.C.
  • 15,340
  • 19
  • 71
  • 102
1

Ok. Thanks for the answers I figured it out...

helpMessage = [NSString stringWithFormat:@"The abasolute value is %i", abs((int)myCGFloat]);

I had tried abs directly on the CGFloat, but I see now that abs is expecting an int value. I thought an unsigned int was the same thing as an absolute value. Thanks for for setting me straight.

John

user278859
  • 10,379
  • 12
  • 51
  • 74