5

I am trying to assign a variable with type 'long long' to a type NSUInteger, What is the correct way to do that?

my code line:

expectedSize = response.expectedContentLength > 0 ? response.expectedContentLength : 0;

where expectedSize is of type NSUInteger and return type of response.expectedContentLength is of type 'long long'. The variable response is of type NSURLResponse.

The compile error shown is:

Semantic Issue: Implicit conversion loses integer precision: 'long long' to 'NSUInteger' (aka 'unsigned int')

Firdous
  • 4,624
  • 13
  • 41
  • 80
  • 1
    You can do an explicit cast, or did you know this and is your question about more than the "how"? Here's the line with the explicit cast: `expectedSize = response.expectedContentLength > 0 ? (NSUInteger)response.expectedContentLength : 0;` – Clafou May 16 '12 at 10:31

2 Answers2

11

you could try the conversion with NSNumber:

  NSUInteger expectedSize = 0;
  if (response.expectedContentLength) {
    expectedSize = [NSNumber numberWithLongLong: response.expectedContentLength].unsignedIntValue;
  }
CarlJ
  • 9,461
  • 3
  • 33
  • 47
5

It's really just a cast, with some range checking:

const long long expectedContentLength = response.expectedContentLength;
NSUInteger expectedSize = 0;

if (NSURLResponseUnknownLength == expectedContentLength) {
    assert(0 && "length not known - do something");
    return errval;
}
else if (expectedContentLength < 0) {
    assert(0 && "too little");
    return errval;
}
else if (expectedContentLength > NSUIntegerMax) {
    assert(0 && "too much");
    return errval;
}

// expectedContentLength can be represented as NSUInteger, so cast it:
expectedSize = (NSUInteger)expectedContentLength;
justin
  • 104,054
  • 14
  • 179
  • 226
  • `< 0` check is not correct. The value -1 means "no expectation that can be arrived at regarding expected content length" (see NSURLResponse.h) – Dmitry Isaev Mar 27 '13 at 15:30
  • @Dmitry added case to example. it's a very specific implementation detail, which would have been caught. it was meant to demonstrate the process, rather than be a perfect and complete implementation (it still is not). – justin Mar 29 '13 at 03:02