简体   繁体   中英

Conversion to Binary - long long and NSUInteger

We need to convert the below datatypes to binary:

  1. Long long to Binary
  2. NSUInteger to Binary

Any help on this would be highly appreciated.

The code i have is :

As per the above link, we have

 - (NSString *) longlongToBinary:(long long) val {

long long num = val;
NSString *res = [NSString string];

for (long long i=63; i>=0; i--)
{

    long long div = 1l<<i;
    if ((num&div)==div) res = [res stringByAppendingString:@"1"];
    else res = [res stringByAppendingString:@"0"];
}

return res;

}

If the val is 20, then the output i am getting is:

0000000000000000000000000001010000000000000000000000000000010100

and this is wrong when i see it in the online convertors.

long is only 32 bits. Since the method is named longlongToBinary , change all of the long variables to long long . That will give you the 64 bits you are using.

Now that you have changed most variables to long long , change the loop variable i back to an int and change the 1l constant to 1ll .

The literal 1l is still only long. That's why you see the output twice. Change the literal to 1ll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM