开发者

objective-c - how to convert between signed base 10 numbers and unsigned base 16

I am wondering how to do converts between unsigned base 16 numbers and signed base 10 numbers?

For example

5d0cfa30041d4348 <-> 6705009029382226760

024025978b5e50d2 <-> 162170919393841362

fb115bd6d34a8e9f <-> -355401917359550817

By the way, they are actually IDs of some items. And internally they are all 64-bit numbers, but in two presentations.

Any clas开发者_如何学Pythonses I can use of ?

Thanks


If the base 16 value is a constant or stored in a variable a simple cast will work.

long long llint1 = (long long int)0x5d0cfa30041d4348;
long long llint2 = (long long int)0x024025978b5e50d2;
long long llint3 = (long long int)0xfb115bd6d34a8e9f;

NSLog(@"\n%lld\n%lld\n%lld", llint1, llint2, llint3);

If the value is a string it will just need to be scanned first.

unsigned long long tmp;
NSScanner *nscanner = [NSScanner scannerWithString:@"0x5d0cfa30041d4348"];
[nscanner scanHexLongLong:&tmp];

llint1 = (long long int)tmp;

nscanner = [NSScanner scannerWithString:@"0x024025978b5e50d2"];
[nscanner scanHexLongLong:&tmp];

llint2 = (long long int)tmp;

nscanner = [NSScanner scannerWithString:@"0xfb115bd6d34a8e9f"];
[nscanner scanHexLongLong:&tmp];

llint3 = (long long int)tmp;

NSLog(@"\n%lld\n%lld\n%lld", llint1, llint2, llint3);

Note: the scanHexLongLong and other scan methods return a BOOL for whether or not the scan was successful. If working with strings it would be best to check that the scan succeeded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜