2

How can i convert an ulong to uint32? A simple cast is not working. What works for me is converting the long to a string and then again parsing the string to an int.

However this seems really wrong. Is there any better way?

oipoistar
  • 477
  • 6
  • 19
  • 1
    What do you mean by "A simple cast is not working" exactly ? What is the exact compiler error message or run-time problem that you are encountering ? – Paul R May 12 '12 at 08:12
  • 1
    Casting a ulong with the value 75 results in an uint32 with the value of 2147483647. – oipoistar May 12 '12 at 08:18
  • 1
    From where are you getting the type `ulong`? What is its definition? What does your cast look like? – Ken Thomases May 12 '12 at 08:31
  • 1
    The value 75 fits into a `unit32` without problem (even a `uint16` or `uint8`) so something is very wrong with your code. – trojanfoe May 12 '12 at 10:13

1 Answers1

4

Like Paul R said, not sure what you mean by "simple cast". Both of the following are working fine for me (and, note, I'm testing with a ULONGLONG).

  1. Direct cast:

    unsigned long long val1 = (unsigned long long)75;
    UInt32 val2 = (UInt32)val1;
    NSLog( @"%qu, %lu", num1, num2 );
    // OUTPUTS: 75, 75

  2. Using NSNumber:

    NSNumber* val1 = [NSNumber numberwithUnsignedLongLong:75];
    NSNumber* val2 = [NSNumber numberwithUnsignedInteger:[val1 usignedIntegerValue]];
    NSLog( @"%qu, %u", [num1 unsignedLongLongValue], [num2 unsignedIntegerValue]];
    // OUTPUTS: 75, 75

GtotheB
  • 2,727
  • 4
  • 21
  • 17